Skip to content

Instantly share code, notes, and snippets.

@norbornen
Created October 1, 2018 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save norbornen/8c6f346f61b31bd490f10bb53da2920c to your computer and use it in GitHub Desktop.
Save norbornen/8c6f346f61b31bd490f10bb53da2920c to your computer and use it in GitHub Desktop.
Превратить массив "плоских" объектов в массив объектов с вложенными детьми
#!/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