Created
October 1, 2018 21:21
-
-
Save norbornen/8c6f346f61b31bd490f10bb53da2920c 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
#!/usr/bin/env node | |
const data = [ | |
{ id: 3, parentId: 1 }, | |
{ id: 2, parentId: 0 }, | |
{ id: 6, parentId: 4 }, | |
{ id: 4, parentId: 1 }, | |
{ id: 7, parentId: 5 }, | |
{ id: 5, parentId: 2 }, | |
{ id: 1, parentId: 0 } | |
]; | |
const seen = {}; | |
while (data.length > 0) { | |
if (data[0]._seen === 1) { | |
break; | |
} | |
const x = data.shift(); | |
const id = x.id; | |
const parentId = x.parentId; | |
seen[id] || (seen[id] = x); | |
if (seen[parentId]) { | |
(seen[parentId].children || (seen[parentId].children = [])).push(x); | |
} else { | |
data.push(x); | |
if (!x.hasOwnProperty('_seen')) { | |
x._seen = 0; | |
} else { | |
x._seen++; | |
} | |
} | |
} | |
console.log(JSON.stringify(data, null, 2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment