How to use for…of Loop In Javascript
For…of loop in JavaScript, is used to iterate over an array of objects. For each object, check and accumulate values under the same key in another object, effectively grouping values by key.
Syntax:
for ( variable of iterableObjectName) {
// code block to be executed
}
Example: In this example we are using uses a for…of loop and a ternary operator to iterate through an array of objects (myArray). It creates a new object (resultObj) by aggregating values under duplicate keys.
const myArray = [
{ key: "id", value: 1 },
{ key: "name", value: "Amit" },
{ key: "id", value: 2 },
{ key: "name", value: "Kohli" },
];
const resultObj = {};
for (const obj of myArray) {
resultObj[obj.key]
? resultObj[obj.key].push(obj.value)
: (resultObj[obj.key] = [obj.value]);
}
console.log(resultObj);
Output
{ id: [ 1, 2 ], name: [ 'Amit', 'Kohli' ] }
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()