Skip to content

Instantly share code, notes, and snippets.

@leonidkuznetsov18
Created July 4, 2020 07:39
Show Gist options
  • Select an option

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

Select an option

Save leonidkuznetsov18/ea98dce1e1f42016e01a19a1f75cffcb to your computer and use it in GitHub Desktop.
convert flat array to tree based on dot name
let array = [{ id: "1", name: "header1" }, { id: "2", name: "header2" }, { id: "1.1", name: "subheader1.1" }, { id: "1.2", name: "subheader1.2" }, { id: "2.1", name: "subheader2.1" }, { id: "2.2", name: "subheader2.2" }, { id: "1.1.1", name: "subheader1detail1" }, { id: "2.1.1", name: "subheader2detail2" }],
result = [];
array.forEach(function (a) {
let parent = a.id.split('.').slice(0, -1).join('.');
this[a.id] = { id: a.id, name: a.name };
if (parent) {
this[parent] = this[parent] || {};
this[parent].items = this[parent].items || [];
this[parent].items.push(this[a.id]);
} else {
result.push(this[a.id]);
}
}, {});
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment