Created
August 31, 2016 15:19
-
-
Save littlee/ce464e9be547e48966ecdaa5c8ecbe99 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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