Reputation: 813
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?
Upvotes: 5
Views: 726
Reputation: 8631
This can be as simple as a recursive reduce.
arr.reduce (function spr (res, cur) {
let obj = {...cur}
let children = obj.children
delete obj.children;
return children.reduce (spr, res).concat ([{
...obj
}])
}, [])
let result = arr.reduce (function spr (res, cur) {
let obj = {...cur}
let children = obj.children;
delete obj.children;
return children.reduce (spr, res).concat ([{
...obj
}])
}, [])
console.log (result)
<script>
var arr = [{
"children": [{
"children": [{
"children": [{
"children": [],
"Id": 1,
"Name": "A",
"Image": "http://imgUrl"
}],
"Id": 1,
"Name": "A",
"Image": "http://imgUrl"
}],
"Id": 2,
"Name": "B",
"Image": "http://imgUrl"
}],
"Id":3,
"Name": "C",
"Image": "http://imgUrl"
}
, {
"children": [{
"children": [{
"children": [],
"Id": 1,
"Name": "A",
"Image": "http://imgUrl"
}],
"Id": 2,
"Name": "B",
"Image": "http://imgUrl"
}],
"Id":3,
"Name": "C",
"Image": "http://imgUrl"
}]
</script>
Upvotes: 4
Reputation: 391
Recursive Reduce:
const fillWithChildren = (a = []) =>
a.reduce(
(result, { children, ...rest }) =>
result
.concat(rest)
.concat(fillWithChildren(children)),
[],
);
fillWithChildren(arr);
Upvotes: 4
Reputation: 28455
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);
Upvotes: 9