Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simplify conversion of nested object into array of objects?

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?

like image 916
RS17 Avatar asked Sep 19 '18 11:09

RS17


1 Answers

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);
like image 135
Nikhil Aggarwal Avatar answered Oct 10 '22 05:10

Nikhil Aggarwal