How to use forEach() In Javascript
forEach() method is used to execute a provided function once for each array element. It is another way to iterate through an array of objects and accumulate values under duplicate keys into a new object.
Example: In this example, we use the forEach() method to iterate through an array of objects (myArray). It accumulates values under duplicate keys, creating a new object (resultObj).
const myArray = [
{ key: "id", value: 1 },
{ key: "name", value: "Alex" },
{ key: "id", value: 2 },
{ key: "name", value: "John" },
];
const resultObj = {};
myArray.forEach(obj => {
if (resultObj[obj.key]) {
resultObj[obj.key].push(obj.value);
} else {
resultObj[obj.key] = [obj.value];
}
});
console.log(resultObj);
Output
{ id: [ 1, 2 ], name: [ 'Alex', 'John' ] }
How to Add Duplicate Object Key with Different Value to Another Object in an Array in JavaScript ?
Adding duplicate object keys with different values to another object in an array in JavaScript refers to aggregating values under the same key from multiple objects in an array, creating a new object where each key corresponds to an array of associated values.
Table of Content
- Using for…of Loop
- Using reduce()
- Using a Map for Multiple Values
- Using forEach()