I have an array of nested objects, and I would like to simplify it a bit and convert it to an object with key, value pairs, so the result would be like this:
Simple Object:
{Groceries: {
'Organic eggs': null,
Fruits: {
Apple: null,
Berries: {
Blueberry: null,
Raspberry: null
}
}
}}
Array of nested objects:
const tree = [{
"id": 1,
"name": "Groceries",
"parentId": null,
"children": [{
"id": 3,
"name": "Organic eggs",
"parentId": 1,
"children": []
}, {
"id": 5,
"name": "Fruits",
"parentId": 1,
"children": [{
"id": 6,
"name": "Apple",
"parentId": 5,
"children": []
},{
"id": 7,
"name": "Berries",
"parentId": 5,
"children": [{
"id": 8,
"name": "Blueberry",
"parentId": 7,
"children": []
},{
"id": 9,
"name": "Raspberry",
"parentId": 7,
"children": []
}]
}]
}]
}]
Using recursion, you can pass your array tree
and loop through it. If you encounter an object in your tree array which has children, you can pass this child array back to your function to build a new simplified object from this sub-array. If the length of the object's children
property is 0
, then you can set the simplified object's name property to be null
.
See example below:
const tree = [{ "id": 1, "name": "Groceries", "parentId": null, "children": [{ "id": 3, "name": "Organic eggs", "parentId": 1, "children": [] }, { "id": 5, "name": "Fruits", "parentId": 1, "children": [{ "id": 6, "name": "Apple", "parentId": 5, "children": [] }, { "id": 7, "name": "Berries", "parentId": 5, "children": [{ "id": 8, "name": "Blueberry", "parentId": 7, "children": [] }, { "id": 9, "name": "Raspberry", "parentId": 7, "children": [] }] }] }] }];
const simplifyObj = arr => {
const obj = {};
for(const {name, children} of arr)
obj[name] = children.length ? simplifyObj(children) : null;
return obj;
}
const simple = simplifyObj(tree);
console.log(simple);
.as-console-wrapper { max-height: 100% !important;} /* ignore */
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments