Skip to content

Instantly share code, notes, and snippets.

@amitkhare
Last active June 2, 2018 07:54
Show Gist options
  • Save amitkhare/4cb42f8a1523d708efe079ece4b28546 to your computer and use it in GitHub Desktop.
Save amitkhare/4cb42f8a1523d708efe079ece4b28546 to your computer and use it in GitHub Desktop.
Generates Tree menu parent>child relation array
const listToTree = (list) => {
var map = {}
var node
var roots = []
var i
for (i = 0; i < list.length; i += 1) {
map[list[i].id] = i // initialize the map
list[i].children = [] // initialize the children
}
for (i = 0; i < list.length; i += 1) {
node = list[i]
if (node.parent_id) {
// if you have dangling branches check that map[node.parent_id] exists
list[map[node.parent_id]].children.push(node)
} else {
roots.push(node)
}
}
return roots
}
var nodes = [
{ id: 1, title:'News', ref: '#', parent_id: 0 },
{ id: 2, title:'Entertainment', ref: '#', parent_id: 0 },
{ id: 3, title:'International', ref: '#', parent_id: 1 },
{ id: 4, title:'National', ref: '#', parent_id: 1 },
{ id: 5, title:'Bollywood', ref: '#', parent_id: 2 },
{ id: 6, title:'Music', ref: '#', parent_id: 2 },
{ id: 7, title:'Hollywood', ref: '#', parent_id: 2 },
{ id: 30, title:'Pakistan', ref: '#', parent_id: 3 },
{ id: 31, title:'Japan', ref: '#', parent_id: 3 },
{ id: 70, title:'Avatar 2', ref: '#', parent_id: 7 },
{ id: 71, title:'Tom Hanks', ref: '#', parent_id: 7 },
{ id: 72, title:'Anil Kapoor', ref: '#', parent_id: 5 },
{ id: 141, title:'Mahoba', ref: '#', parent_id: 73 },
{ id: 73, title:'Uttar Pradesh', ref: '#', parent_id: 4 },
{ id: 130, title:'James Camroon', ref: '#', parent_id: 70 }
]
return response.status(200).json(listToTreen(nodes))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment