Home > front end >  How to merge 2 arrays of object with extra matching
How to merge 2 arrays of object with extra matching

Time:10-27

I actually don't know what this is called, hence the "extra matching" in the title

I have 2 arrays of objects

[{player_1: 'adeshina'}, {player_1: 'MindReaper'}]

and

[{player_2: 'thinkerbull'}, {player_2: 'AfroGamer'}]

How can I merge it to become {player_1: 'adeshina', player_2: 'thinkerbull'}, {player_1: 'MindReaper', player_2: 'AfroGamer'} ?

CodePudding user response:

You can use map() to loop through the arrays and merge the objects,

like this:

const arrayOne = [{player_1: 'adeshina'}, {player_1: 'MindReaper'}]
const arrayTwo = [{player_2: 'thinkerbull'}, {player_2: 'AfroGamer'}]

const newArray = arrayOne.map( (e, index) => ({...e, ...arrayTwo[index]}));

CodePudding user response:

It's actually called "zipping". You wanna zip two arrays.

It can be done using map:

var a = [{player_1: 'adeshina'}, {player_1: 'MindReaper'}]
var b = [{player_2: 'thinkerbull'}, {player_2: 'AfroGamer'}]


var c = a.map(function(e, i) {
  return [e, b[i]];
});

console.log(c)

A shorter version would be:

c = a.map((e, i) =>[e, b[i]]);
  • Related