Home > Blockchain >  Iterate through nested objects Array to get ID and Name
Iterate through nested objects Array to get ID and Name

Time:09-15

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

CodePudding user response:

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.

CodePudding user response:

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;
}
  • Related