To map two arrays of objects in JavaScript, you can use the map() function along with other array methods such as reduce() or find() to combine the objects based on a common key.

Mapping two arrays with a common ID #

Suppose, we have two arrays.

<script>
 let name = [{id:1, name:"Red"}, {id:2, name:"Yellow"}];
 let code = [{id:1, code: "#ff0000"}, {id:2, code: "#ffff00"}]
</script>

We want to map over these two arrays and get one array like this.

let fullData = [{id:1, name:"Red", code: "#ff0000"}, {id:2, name:"Yellow", code: "#ffff00"}]

We can achieve this using the following code.

<script>
 let array1 = [{id:1, name:"Red"}, {id:2, name:"Yellow"}];
 let array2 = [{id:1, code: "#ff0000"}, {id:2, code: "#ffff00"}]
 
 let newArray = array1.map(obj1 => { 
  let obj2 = array2.find(obj2 => obj2.id === obj1.id); 
  return { ...obj1, ...obj2 }; 
});

console.log(newArray);
</script>