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
How to Create Array of Objects From Keys & Values of Another Object in JavaScript ?
Creating an array of objects from the keys and values of another object involves transforming the key-value pairs of the original object into individual objects within an array. Each object in the array represents a key-value pair from the source object. Below approaches can be used to accomplish th
3 min read
How to Append an Object as a Key Value in an Existing Object in JavaScript ?
In JavaScript, An object is a key-value pair structure. The key represents the property of the object and the value represents the associated value of the property. In JavaScript objects, we can also append a new object as a Key-value pair in an existing object in various ways which are as follows.
3 min read
How to Merge two Different Arrays of Objects with Unique Values in JavaScript?
Merging two arrays of objects with unique values is a common task in JavaScript. This operation involves combining the elements of two arrays while ensuring that each resulting object has a unique identifier. We will explore various approaches to merging two arrays of objects with unique values. The
4 min read
How to Add an Image File to an Object of an Array in JavaScript ?
In JavaScript adding the image files into objects within an array is essential for managing and organizing data in web development. This practice is particularly valuable when dealing with collections of objects, each requiring an associated image. There are various ways to add an image file to an o
3 min read
How to Convert an Object into Array of Objects in JavaScript?
Here are the different methods to convert an object into an array of objects in JavaScript1. Using Object.values() methodObject.values() method extracts the property values of an object and returns them as an array, converting the original object into an array of objects.JavaScriptconst a = { java:
3 min read
How to use forEach with an Array of Objects in JavaScript ?
Using the forEach() method with an array of objects in JavaScript is essential for iterating over collections and performing operations on each object. This guide explores effective techniques to utilize forEach() for array manipulation, enhancing your coding skills. Syntax: array.forEach( function(
3 min read
How to modify an object's property in an array of objects in JavaScript ?
Modifying an object's property in an array of objects in JavaScript involves accessing the specific object within the array and updating its property.Using the Array.map() methodUsing the map() method to create a new array by transforming each element of the original array based on a specified funct
5 min read
How to Move a Key in an Array of Objects using JavaScript?
The JavaScript array of objects is a type of array that contains JavaScript objects as its elements.You can move or add a key to these types of arrays using the below methods in JavaScript:Table of ContentUsing Object Destructuring and Map()Using forEach() methodUsing for...of LoopUsing reduce() met
5 min read
How to Create an Array of Object Literals in a Loop using JavaScript?
Creating arrays of object literals is a very frequent activity in JavaScript, as often when working with data structures, several objects are needed. This article will allow your hand through different ways of coming up with an array of object literals in a loop in JavaScript. Here are different app
5 min read
How to Convert Array of Objects into Unique Array of Objects in JavaScript ?
Arrays of objects are a common data structure in JavaScript, often used to store and manipulate collections of related data. However, there are scenarios where you may need to convert an array of objects into a unique array, removing any duplicate objects based on specific criteria. JavaScript has v
8 min read