繁体   English   中英

缩进 object 嵌套对象数组中的值 JavaScript

[英]Indent object values in an array of nested objects in JavaScript

我有一个这样的数组

[
  {
    name: 'foo',
    nestedArray: [
      {
        name: 'bar',
        nestedArray: []
     }
    ]
  }
]

拥有像这样的展平阵列的最佳方法是什么?

[
  {
    name: 'foo',
    nestedArray: [
      {
        name: 'bar',
        nestedArray: []
     }
    ]
  },
  {
    name: '  bar',
    nestedArray: []
  }
]

您可以尝试迭代输入数组并将嵌套数组对象移出到外部数组中。 我希望这会按照您的期望工作

 // Input array const inputArray = [ { name: 'foo', nestedArray: [ { name: 'bar', nestedArray: [] } ] } ]; // Result array const res = []; // Iterating input array and moving out nested array objects into outer one. inputArray.forEach((obj) => { res.push(obj); obj.nestedArray.forEach((nestedObj) => { res.push(nestedObj); }); }); // Assigning result console.log(res);

暂无
暂无

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

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