简体   繁体   English

如何从 JavaScript 中的嵌套数组对象中提取特定属性作为数组

[英]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.基本上我想遍历每个对象以获取所有“Id”属性值作为数组。 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',...]输出应该像 - ['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.你可以返回一个带有 id 的数组和一个孩子的平面数组。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从JSON返回嵌套在对象中的嵌套JavaScript数组的属性值? - How can I return the property values of a nested JavaScript array nested in an object from JSON? 如何从 object 中提取引脚属性并在 JavaScript 中制作引脚数组? - How can I extract pin property from an object and make an array of pins in JavaScript? 如何通过从单独的数组中匹配的字符串对象值从 3 个嵌套的 json 数组中提取对象值,然后在 html/javascript 中显示它 - How can I extract object values from 3 nested json arrays by matched string object values from a separate array and then display it in html/javascript 如何将 JavaScript object 的属性值提取到数组中? - How might I extract the property values of a JavaScript object into an array? 如何从对象javascript数组创建特定对象? - How can I create a specific object from an array of objects javascript? 如何将嵌套的对象数组转换为平面数组 javascript - How Can I convert a nested array of object into a flat Array javascript 如何从 javascript 中的 object 数组中提取特定属性(即键/值)? - how to extract particular property(i.e key/value) from array of object in javascript? 如何使用javascript从对象数组中提取对象的值 - How can I extract the value of an object from an array of objects array using javascript 如何使用javascript嵌套对象数组中的另一个属性值设置特定属性值? - How to set specific property value with another property value in a javascript nested object array? 如何在嵌套数组中提取数组的属性 - How to extract property of array in nested array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM