簡體   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