Loop through the array to take out the desired data and encapsulate it into an array of objects

could you tell me how to iterate through the desired data in the following array? Take out the name and id from the following array and put them in an array of objects; arrNew = [{id:1, name: "system Settings"}, {id:39, name: "menu Management"}, {id:36, name: "menu details"},.]

let arr = [
    {
        "appId":1001,
        "id":1,
        "name":"",
        "nodes":[
            {
                "appId":1001,
                "id":38,
                "name":"",
                "nodes":[
                    {
                        "appId":1001,
                        "id":36,
                        "name":"",
                    }
                ]
            },
            {
                "appId":1001,
                "id":2,
                "name":"",
                "nodes":[

                ]
            },
        ]
    },
    {
        "appId":1001,
        "id":439,
        "name": ""
        "nodes":[
            {
                "id":440,
                "name":"",
                "nodes":[

                ]
            }
        ]
    }
];

mainly hope to get a more efficient method.

Mar.04,2021

use recursion.

let arr2=[];
function run(arr){
        if(arr.length>0){
        arr.forEach(v=>{
            let md={};
            md.id=v.id;
            md.name=v.name;
            arr2.push(md)
            if(v.nodes){
                run(v.nodes)
            }                
        })
    }
    return arr2;
}

wrote it for you. You have a node without name, and the name I deconstructed defaults to an empty string:


let arr = [
    {
        "appId":1001,
        "id":1,
        "name":"",
        "nodes":[
            {
                "appId":1001,
                "id":38,
                "name":"",
                "nodes":[
                    {
                        "appId":1001,
                        "id":36,
                        "name":"",
                    }
                ]
            },
            {
                "appId":1001,
                "id":2,
                "name":"",
                "nodes":[

                ]
            },
        ]
    },
    {
        "appId":1001,
        "id":439,
        "nodes":[
            {
                "id":440,
                "name":"",
                "nodes":[

                ]
            }
        ]
    }
];

const result = [];
arr.forEach( ({id, name = '', nodes}) => {
    result.push({
        id,
        name
    })
    nodes.forEach( ({id, name = ''}) => {
        result.push({
            id,
            name
        })
    })
})

console.log(result);

var newarr= [];

        for(var i=0;i<arr.length;iPP){
            var temp={"id":arr[i]["id"],"name":arr[i]["name"]};
            newarr.push(temp);
        }
        console.log(newarr)

I hope to solve your problem;

Menu