繁体   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