Ali Asghar
Ali Asghar

Reputation: 1

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:

Upvotes: 0

Views: 769

Answers (3)

Rajneesh
Rajneesh

Reputation: 5308

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));

Upvotes: 0

Med Jelidi
Med Jelidi

Reputation: 19

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

Upvotes: 1

Architect Jamie
Architect Jamie

Reputation: 2579

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.

Upvotes: 0

Related Questions