簡體   English   中英

JS 一行 'for' 和 'push' 到數組

[英]JS one line 'for' and 'push' to array

我有一個這樣的數組:

const matches = [
  {homeId: 123, awayId: 345},
  {homeId: 4343, awayId: 675},
  {homeId: 888, awayId: 999}
];

然后我想要一個包含所有Id的新數組。 所以我有這個代碼:

let players = [];
for (m of matches) {    
  players.push(...[m.homeId, m.awayId]);
}

有可能在一行中做同樣的事情嗎? 類似於 javascript map的東西(在我的示例中,我不能使用 map,因為最終數組的長度不同)。 像這樣的東西:

const players = for (m of matches) {    
  players.push(...[m.homeId, m.awayId]);
}

您可以使用 map 每個 object 到其值Object.values ,然后用.flat()展平:

 const matches = [ {homeId: 123, awayId: 345}, {homeId: 4343, awayId: 675}, {homeId: 888, awayId: 999} ]; const ids = matches.map(Object.values).flat(); console.log(ids);

或使用flatMap

 const matches = [ {homeId: 123, awayId: 345}, {homeId: 4343, awayId: 675}, {homeId: 888, awayId: 999} ]; const ids = matches.flatMap(Object.values); console.log(ids);

您可以使用.reduce()

 const matches = [ {homeId: 123, awayId: 345}, {homeId: 4343, awayId: 675}, {homeId: 888, awayId: 999} ]; let result = matches.reduce((a,v) => [...a, v.homeId, v.awayId],[]) console.log(result);

您可以 map 直接平展結果。

 const matches = [{ homeId: 123, awayId: 345 }, { homeId: 4343, awayId: 675 }, { homeId: 888, awayId: 999 }], players = matches.flatMap(({ homeId, awayId }) => [homeId, awayId]); console.log(players);

如果您想從對象中獲取所有值,您可以對這些值進行平面映射。 值的順序由 inserteatimn 順序和鍵值定義。 數組之類的索引,如正 32 位 integer 值首先排序,然后是所有其他字符串。 最后,您將獲得所有以Symbols為鍵的值。

 const matches = [{ homeId: 123, awayId: 345 }, { homeId: 4343, awayId: 675 }, { homeId: 888, awayId: 999 }], players = matches.flatMap(Object.values); console.log(players);

你可以使用reduce

 const matches = [ {homeId: 123, awayId: 345}, {homeId: 4343, awayId: 675}, {homeId: 888, awayId: 999} ]; const ids = matches.reduce(function(accumulator, item){ accumulator.push(...[item.homeId, item.awayId]); return accumulator;}, []); console.log(ids);

暫無
暫無

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

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