I have as nested json object like this
{
"id": 1,
"parentId": null,
"name": "Product",
"children": [
{
"id": 50,
"parentId": 1,
"name": "Bicycle",
"children": [
{
"id": 100,
"parentId": 50,
"name": "Tire"
}
]
}
]
}
Oddly I have figured out how to build the nested tree from the result but not how to reverse it.
I have tried using lodash _.flatten and _.flattendeep
but having one of those days where I can't get my head around this. Also the object can be of unknown depth. Any thoughts ?
My desired result is this.
[
{"id" : 1, "parentId" : null, "Product" },
{"id" : 50, "parentId" : 1 , "Bicycle"},
{"id" : 100, "parentId" : 50 , "Tire"}
]
not a very optimal solution but just an idea, NOTE: if dataset is very large there might be some performance issues.
resultsArray = [];
function flatten(obj) {
const { id, parentId, name, children} = obj;
if(children && children.length) {
children.map(child => flatten(child));
}
resultsArray.push({id, parentId, name});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.