简体   繁体   中英

How can I extract specific property as an array from nested array object in JavaScript

Basically I wanted to iterate over each object to get all "Id" property value as an array. My object structure is like-

    {
    Id:'1',
    children:[
        {
            Id:'2',
            children:[{...},{...},...]
        },
        {
            Id:'5',
            children:[
                {
                    Id:'6',
                    children:[{ Id:'7',...},{Id:'8',...}]
                },
                {
                    Id:'9',
                    children:[{...},{...}]
                },
                {...},
                {...},
                .
                .
                .
            ]
        },
        {...}
    ]
}

Output should be like- ['1','2','3',...'9',...]

I am trying with recursion.

  idArr = [];
  getIds(arr) {
    (arr || []).forEach(obj => {
      this.idArr.push(obj.Id);
      this.getIds(obj.children)
    })
  }

Is there any better approach? If anyone can help it would be nice.

You could return an array with id and a flat array of the children.

 function getIds(object) { return [object.Id, ...(object.children || []).flatMap(getIds)]; } var data = { Id:'1', children: [{ Id:'2', children: [] }, { Id:'5', children:[{ Id:'6', children:[{ Id: '7' }, { Id:'8' }] }, { Id:'9', children: [] }] }] }; console.log(getIds(data));

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