Skip to content

Instantly share code, notes, and snippets.

@DenimTornado
Created May 15, 2018 11:39
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 DenimTornado/0e44a41e4144504466242c57ebe25397 to your computer and use it in GitHub Desktop.
Save DenimTornado/0e44a41e4144504466242c57ebe25397 to your computer and use it in GitHub Desktop.
Convert comments list into nested object with Array.reduce
const comments = [
{
id: 1,
text: 'Комментарий 1',
parent_id: 0,
},
{
id: 12,
text: 'Комментарий 12',
parent_id: 3,
},
{
id: 8,
text: 'Комментарий 8',
parent_id: 3,
},
{
id: 3,
text: 'Комментарий 3',
parent_id: 0,
},
{
id: 24,
text: 'Комментарий 24',
parent_id: 12,
}
];
const tree = comments.reduce(function(root, comm) {
if (root[comm.id] && root[comm.id].children) { //сохраняем дочерние комменты, если он уже есть
comm.children = root[comm.id].children;
}
//собираем ноду
root[comm.id] = comm;
root[comm.parent_id] = root[comm.parent_id] || {};
root[comm.parent_id].children = root[comm.parent_id].children || [];
root[comm.parent_id].children.push(comm);
return root;
}, {})[0].children; //кладём в tree элемент с ключом 0, то есть корневой элемент
console.log(tree);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment