Skip to content

Instantly share code, notes, and snippets.

@leonidkuznetsov18
Last active July 4, 2020 07:40
Show Gist options
  • Select an option

  • Save leonidkuznetsov18/11eb1758fa89a480938ee116d738f003 to your computer and use it in GitHub Desktop.

Select an option

Save leonidkuznetsov18/11eb1758fa89a480938ee116d738f003 to your computer and use it in GitHub Desktop.
convert flat array to tree based on id only
const numberingArr = [
{ilvl: "0", numId: "1", text: "Sdvs"},
{ilvl: "0", numId: "1", text: "verFFE"},
{ilvl: "1", numId: "1", text: "235rf"},
{ilvl: "0", numId: "2", text: "Hrg"},
{ilvl: "1", numId: "2", text: "Gtegwr"},
{ilvl: "1", numId: "2", text: "ser"}
];
const numberingTree = [];
for (const element of numberingArr) {
const existingElementById = numberingTree.find(item => item.numId === element.numId);
if (existingElementById) {
const existingElementByILvl = existingElementById.levels.find(item => item.ilvl === element.ilvl);
if (existingElementByILvl) {
existingElementByILvl.children.push({
text: element.text
});
} else {
existingElementById.levels.push({
ilvl: element.ilvl,
children: [
{
text: element.text
}
]
});
}
} else {
numberingTree.push({
numId: element.numId,
levels: [
{
ilvl: element.ilvl,
children: [
{
text: element.text
}
]
}
]
});
}
}
// FROM
// [
// {ilvl: "0", numId: "1", text: "Sdvs"},
// {ilvl: "0", numId: "1", text: "verFFE"},
// {ilvl: "1", numId: "1", text: "235rf"},
// {ilvl: "0", numId: "2", text: "Hrg"},
// {ilvl: "1", numId: "2", text: "Gtegwr"},
// {ilvl: "1", numId: "2", text: "ser"}
// ]
// TO
// [
// {
// numId: "1",
// levels: [
// {
// ilvl: "0",
// children: [
// {
// text: "Sdvs",
// },
// {
// text: "verFFE",
// }
// ]
// },
// {
// ilvl: "1",
// children: [
// {
// text: "235rf",
// }
// ]
// }
// ]
// },
// {
// numId: "2",
// levels: [
// {
// ilvl: "0",
// children: [
// {
// text: "Hrg",
// }
// ]
// },
// {
// ilvl: "1",
// children: [
// {
// text: "Gtegwr",
// },
// {
// text: "ser",
// }
// ]
// }
// ]
// }
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment