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>
Comments (1)
How to map two array of objects in JavaScript
https://www.3schools.in/p/embed.html?q=CjxzY3JpcHQ+CiBjb25zdCBhcnJheTEgPSBbCiAgeyBpZDogMSwgdmFsdWU6ICdBJyB9LAogIHsgaWQ6IDIsIHZhbHVlOiAnQicgfSwKICB7IGlkOiAzLCB2YWx1ZTogJ0MnIH0KIF07CgogY29uc3QgYXJyYXkyID0gWwogIHsgaWQ6IDEsIGxhYmVsOiAnQWxwaGEnIH0sCiAgeyBpZDogMiwgbGFiZWw6ICdCZXRhJyB9LAogIHsgaWQ6IDMsIGxhYmVsOiAnR2FtbWEnIH0KIF07CgogY29uc3QgbWFwcGVkQXJyYXkgPSBhcnJheTEucmVkdWNlKChyZXN1bHQsIG9iajEpID0+IHsKICBjb25zdCBtYXRjaGluZ09iaiA9IGFycmF5Mi5maW5kKG9iajIgPT4gb2JqMi5pZCA9PT0gb2JqMS5pZCk7CiAgaWYgKG1hdGNoaW5nT2JqKSB7CiAgICByZXN1bHQucHVzaCh7IC4uLm9iajEsIC4uLm1hdGNoaW5nT2JqIH0pOwogIH0KICByZXR1cm4gcmVzdWx0OwogfSwgW10pOwoKIGNvbnNvbGUubG9nKG1hcHBlZEFycmF5KTsKPC9zY3JpcHQ+
In this approach, the reduce() function iterates over the array1 elements, and for each object, it searches for a matching object in array2 using find(). If a matching object is found, it creates a new object by combining properties from both objects using the spread operator and pushes it to the result array.