This is my nested Object
var arr = [{
"children": [{
"children": [{
"children": [],
"Id": 1,
"Name": "A",
"Image": "http://imgUrl"
}],
"Id": 2
"Name": "B",
"Image": "http://imgUrl"
}],
"Id":3,
"Name": "C",
"Image": "http://imgUrl"
}]
I wanted to convert the above to the following format
[{
"Name": "C",
"Id": 3,
"Image": "http://imgUrl"
}, {
"Name": "B",
"Id": 2,
"Image": "http://imgUrl"
}, {
"Name": "A",
"Id": 1,
"Image": "http://imgUrl"
}]
I wrote below code to do this
var newArr = []
function getNestedObj(obj){
if(obj.length){
for ( var i=0; i<obj.length; i++){
var newObj = {};
newObj.Name = obj[i].Name;
newObj.Id = obj[i].Id;
newObj.Image = obj[i].Image;
newArr.push(newObj);
if(obj[i].children.length !=0 ){
getNestedObj(obj[i].children)
}
else {
return newArr;
}
}
}
}
I want to simplify the above function? How can I achieve this?
Try following
let arr = [{"children":[{"children":[{"children":[],"Id":1,"Name":"A","Image":"http://imgUrl"}],"Id":2,"Name":"B","Image":"http://imgUrl"}],"Id":3,"Name":"C","Image":"http://imgUrl"}];
function fillWithChildren(a, r=[]) {
a.forEach(({children, ...rest}) => {
r.push(rest);
if(children) fillWithChildren(children, r);
});
return r;
}
let result = fillWithChildren(arr);
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With