Created
November 2, 2020 19:50
-
-
Save dmjcomdem/3996057e1807950e3780018ed60bf8e5 to your computer and use it in GitHub Desktop.
Преобразование в иерархическую структуру
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
const source = [ | |
{ id: 1 }, | |
{ id: 3, parentId: 1 }, | |
{ id: 4, parentId: 3 }, | |
{ id: 5, parentId: 3 }, | |
{ id: 6, parentId: 1 }, | |
{ id: 7, parentId: 6 }, | |
{ id: 8, parentId: 7 }, | |
{ id: 9, parentId: null } | |
]; | |
const res = source | |
.map(item => Object.assign( {}, item )) | |
.reduce((acc, curr, index, arr) => { | |
if (curr.parentId) { | |
let parent = arr.find(item => item.id === curr.parentId); | |
(parent.children = parent.children || []).push(curr); | |
} else { | |
acc.push(curr); | |
} | |
return acc; | |
}, []); | |
console.log(res); | |
/** | |
[ | |
{ | |
"id": 1, | |
"children": [ | |
{ | |
"id": 3, | |
"parentId": 1, | |
"children": [...] | |
}, | |
{ | |
"id": 6, | |
"parentId": 1, | |
"children": [...] | |
} | |
] | |
}, | |
{ | |
"id": 9, | |
"parentId": null | |
} | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment