Question
I have a flat array of objects I'd like to turn into a nested tree. I've tried using both recursion and reduce but haven't quite got the desired effects.
Specifically I have the array:
const rawdata = [
{name: "A", parent: "All", value: null},
{name: "C", parent: "A", value: 10},
{name: "D", parent: "A", value: 20},
{name: "E", parent: "A", value: 30},
{name: "B", parent: "All", value: null},
{name: "F", parent: "B", value: 10},
{name: "G", parent: "B", value: 20},
{name: "H", parent: "B", value: 30}
]
Desired Result
And I'd like to turn this into:
let result = {name: "All",
children:
[
{name: "A",
children: [
{name: "C", value: 10},
{name: "D", value: 20},
{name: "E", value: 30},
],
value: null,
},
{name: "B",
children: [
{name: "F", value: 10},
{name: "G", value: 20},
{name: "H", value: 30},
],
value: null
}
]
}
What I've tried:
I've been able to use recursion to create a tree where All
is at the top most layer using the name
and parent
values, but I haven't been able to figure out how to retain the values
as part of the object.
let makeTree = (categories, parent) => {
let node = {}
categories
.filter(c => c.parent === parent)
.forEach(c => node[c.name] =
makeTree(categories, c.name))
return node
}
console.log(JSON.stringify(makeTree(rawdata, "All")), null, 2)
tried applying code from this post Create an tree of objects from arrays but my scenario is a bit different. Any help appreciated!
I also tried using: Build tree array from flat array in javascript
const nest = (items, id = null, link = 'parent_id') =>
items
.filter(item => item[link] === id)
.map(item => ({ ...item, children: nest(items, item.id) }));
console.log(nest(rawdata, id = 'name', link = 'parent'))
But couldn't get this to work either?