Skip to content

Instantly share code, notes, and snippets.

@DenimTornado
Last active May 15, 2018 11:36
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/1933ecce39de742b7f714db0c5dd0128 to your computer and use it in GitHub Desktop.
Save DenimTornado/1933ecce39de742b7f714db0c5dd0128 to your computer and use it in GitHub Desktop.
Convert comments list into nested object with for
const comments2 = [
{
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,
}
];
let tree2 = {};
const obj = {};
const len = comments2.length;
for (let i = 0; i < len; i++) {
const comm = comments2[i];
if (obj[comm.id] && obj[comm.id].children) { //сохраняем дочерние комменты, если он уже есть
comm.children = obj[comm.id].children;
}
//собираем ноду
obj[comm.id] = comm;
obj[comm.parent_id] = obj[comm.parent_id] || {};
obj[comm.parent_id].children = obj[comm.parent_id].children || [];
obj[comm.parent_id].children.push(comm);
}
tree2 = obj[0].children; //кладём в tree элемент с ключом 0, то есть корневой элемент
console.log(tree2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment