简体   繁体   中英

JS one line 'for' and 'push' to array

I have an array like this:

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

Then I want a new array with all Id . So I have this code:

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

It's possible to do the same in one line? Something similar to javascript map (in my example I can't use map because final array has different length). Something like this:

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

You can map each object to its values with Object.values , then flatten with .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);

Or with flatMap :

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

You can use .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);

You could map with directly flatting the result.

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

If you like to get all values from the objects, you could flatmap the values. The order of the values is defined by the inserteatimn order and the key values. Array like indices like positive 32 bit integer values are sorted first and then comes all other strings. At the end you get all values with Symbols as keys.

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

you can use 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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