簡體   English   中英

從對象數組獲取對象數組內的數組 - 到新的對象數組

[英]Get Array inside Array of Object from Array of Objects - to new Array of Objects

我有以下對象數組:

 const arr = [ { Name: 'TestName', Age: 50, OtherStuff: [ { MainID: 1111, ParrentId: 1122 }, { MainID: 2222, ParrentId: 2233 } ], Animal: 'Dog' }, { Name: 'TestName2', Age: 20, OtherStuff: [ { MainID: 3333, ParrentId: 3344 } ], Animal: 'Cat' } ]

我想要這個結果:

 newArr = [{ MainID: 1111, ParrentId: 1122 }, { MainID: 2222, ParrentId: 2233 }, { MainID: 3333, ParrentId: 3344 }]

如何在對象數組的每個對象中獲取每個數組並將其放入新的對象數組中?

  • 克里斯

在一行中使用reduce方法。

 const arr = [ { Name: 'TestName', Age: 50, OtherStuff: [ { MainID: 1111, ParrentId: 1122 }, { MainID: 2222, ParrentId: 2233 } ], Animal: 'Dog' }, { Name: 'TestName2', Age: 20, OtherStuff: [ { MainID: 3333, ParrentId: 3344 } ], Animal: 'Cat' } ]; const updated = arr.reduce((acc, curr) => [...acc, ...curr.OtherStuff], []); console.log(updated);

以下是執行此操作的眾多方法之一:

 const arr = [{ el: [1, 2] }, { el: [3] }, { el: 4 }] console.log(arr.flatMap(e => e.el))

有關更多信息,請參閱array.flatMap參考,包括有關reduceconcat方法的警告。

當你想從另一個給定的對象數組中生成一個對象數組時,你可以使用 map 函數:

var newArr = arr.map(obj => {
  return obj.OtherStuff;
}).flat();

您結合 flat 方法來生成統一的對象數組而不是數組數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM