Skip to content

Instantly share code, notes, and snippets.

@littlee
Created August 31, 2016 15:19
Show Gist options
  • Save littlee/ce464e9be547e48966ecdaa5c8ecbe99 to your computer and use it in GitHub Desktop.
Save littlee/ce464e9be547e48966ecdaa5c8ecbe99 to your computer and use it in GitHub Desktop.
var data = [
{
id: 2,
name: 'c',
parent: 0
},
{
id: 3,
name: 'd',
parent: 1
},
{
id: 0,
name: 'a',
parent: null
},
{
id: 1,
name: 'b',
parent: 0
},
{
id: 4,
name: 'e',
parent: 1
},
{
id: 5,
name: 'f',
parent: null
}
]
var dataMap = {}
for (var i = 0; i < data.length; i++) {
dataMap[data[i].id] = []
for (var j = 0; j < data.length; j++) {
if (i !== j && data[j].parent === data[i].id) {
dataMap[data[i].id].push(data[j])
}
}
}
for (var k = 0; k < data.length; k++) {
data[k].children = dataMap[data[k].id]
}
data = data.filter((item) => {
return item.parent === null;
})
// console.log(dataMap);
console.log(JSON.stringify(data, null, 4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment