Created
July 4, 2020 07:39
-
-
Save leonidkuznetsov18/ea98dce1e1f42016e01a19a1f75cffcb to your computer and use it in GitHub Desktop.
convert flat array to tree based on dot name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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