I have the following, nested, json structure:
{
element: "a",
items: ["l1", "l2"],
children: [{
element: "b",
children: [{
element: "c",
items: ["l3"]
}, {
element: "b",
child: {
element: "c",
items: ["l4"]
}
}
Basically:
I'd like to process this json to get a flat array containing all the items:
const finalArray = parse(json); //returns ["l1","l2","l3","l4"]
Is there any elegant way to achieve this with mapping/filter functions?
const getItems = (acc = [], { items = [], child = {}, children = [] }) =>
[
...acc,
...items,
...(child?.items || []),
...(children.length ? children.reduce(getItems, acc) : [])
];
const data = {
element:"a",
items: ["l1","l2"],
children: [
{
element: "b",
children: [
{ element: "c", items: ["l3"] },
{ element: "b", child: { element: "c", items: ["l4"] } }
]
}
]
}
console.log( getItems([], data) );