How to Add Duplicate Object Key with Different Value to Another Object in an Array in JavaScript ?
Last Updated :
24 Jun, 2024
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.
Using for...of Loop
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.
JavaScript
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' ] }
Using reduce()
Reduce() method is used to iterate through an array of objects. It accumulate values under duplicate keys into a new object. If a key already exists, append the value; otherwise, create a new key-value pair.
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr),
initialValue )
Example: In this example we are using reduce() method to iterate through an array of objects (myArray). It accumulates values under duplicate keys, creating a new object (resultObj).
JavaScript
const myArray = [
{ key: "id", value: 1 },
{ key: "name", value: "Bhavna" },
{ key: "id", value: 2 },
{ key: "name", value: "Sharma" },
];
const resultObj = myArray.reduce((acc, obj) => {
acc[obj.key] ? acc[obj.key].push(obj.value) : (acc[obj.key] = [obj.value]);
return acc;
}, {});
console.log(resultObj);
Output{ id: [ 1, 2 ], name: [ 'Bhavna', 'Sharma' ] }
Using a Map for Multiple Values
Utilize a Map object to store multiple values for the same key. Initialize the key with an empty array, then push values into it. This approach allows for efficient storage and retrieval of key-value pairs with duplicate keys.
Example: The function addValueToKey adds values to a Map under the same key. For key 'key', it stores ['value1', 'value2']. Printing the map outputs the entries.
JavaScript
let map = new Map();
// Function to add a value to a key
function addValueToKey(key, value) {
if (!map.has(key)) {
map.set(key, []);
}
map.get(key).push(value);
}
// Add values to the same key
addValueToKey('key', 'value1');
addValueToKey('key', 'value2');
// Print the Map
console.log(Array.from(map.entries()));
Output[ [ 'key', [ 'value1', 'value2' ] ] ]
Using forEach()
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).
JavaScript
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' ] }
Using Object.entries() and forEach()
Another approach to aggregating values under the same key from multiple objects in an array is by utilizing Object.entries() in combination with forEach(). This method iterates over the entries of each object, grouping the values by key into a new object.
Example:
JavaScript
function aggregateValues(arr) {
const resultObj = {};
arr.forEach(obj => {
Object.entries(obj).forEach(([key, value]) => {
if (resultObj[key]) {
resultObj[key].push(value);
} else {
resultObj[key] = [value];
}
});
});
return resultObj;
}
const myArray = [
{ a: 1, b: 2 },
{ a: 3, b: 4, c: 5 },
{ a: 6, c: 7 }
];
const resultObj = aggregateValues(myArray);
console.log(resultObj);
Output{ a: [ 1, 3, 6 ], b: [ 2, 4 ], c: [ 5, 7 ] }
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read