简体   繁体   中英

Iterate through nested objects Array to get ID and Name

components: any = [
    {
      id: "17:12610",
      name: "custom-component",
      hasWarning: true,
      selectableKey: 'id',
      preview: 'thumbnailLink',
      children: {
        "17:12610": {
          "name": "cc-1",
          "type": "instance",
          "children": {
            "7:43": {
              "name": "icon-slot",
              "children": {},
              "type": "div"
            }
          }
        }
      }
    }
  ];

Object.keys(this.components[0].children).forEach((res) => {
      console.log(res);
    });

I am iterating like this but its only giving me the first ID. I want to get each children ID & Name. Also I want to track the index so that I can make changes on particular index

I want the output like this:

  • id : 17:12610 name : cc-1
  • id : 7:43 name : icon-slot

You are specifying components[0] before your forEach function. If you have multiple elements in your components array then you will need something like:

(this.components).forEach((root => {
      (root.children).forEach((child) => {
          console.log('id:' + child + ' name:' + child.name);
    }
  }
);

Also, looking at your array construction, you have created an array of objects, not an array of key value pairs and so they will not have a key associated with them. If you want keys associated with them, change your object {} to a nested array [].

You edited your question to add the desired output format. I edited my answer accordingly.

let child = components[0].children;
while (child) {
  const id = Object.keys(child)[0];
  const name = child[id].name;
  console.log('id: ' + id + ' name: ' + name);
  child = child[id].children;
}

You can create a recursive function to achieve the solution. Something like this:

 const component = [{"id":"17:12610","name":"custom-component","hasWarning":true,"selectableKey":"id","preview":"thumbnailLink","children":{"17:12610":{"name":"cc-1","type":"instance","children":{"7:43":{"name":"icon-slot","children":{},"type":"div"}}}}}]; const recursive = (arr, formedArr=[]) => arr.reduce((a,e)=>{ Object.entries(e.children || e).forEach(([id, {name, children}])=>{ a.push({id, name}); if(children) recursive([children], a); }); return a; },formedArr); console.log(recursive(component));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM