EN
JavaScript - merge objects in array with the same keys
0
points
In this article, we would like to show you how to merge objects in an array with the same keys in JavaScript.
To solve the problem, in the example below we use the following methods:
forEach()- to iterate over all objects insidearray,filter()- to check if an object with a giventypeproperty value already exists,concat()- if an object with a giventypealready exists, the current objectvaluesare added to it usingconcat()method.- additionally, we use
typeofoperator to check ifvaluescontain a single value and convert it to an array when necessary.
Practical example
// ONLINE-RUNNER:browser;
const array = [
{ type: 1, values: 'a' },
{ type: 1, values: ['b', 'c'] },
{ type: 2, values: 'd' }
];
const result = [];
array.forEach((object) => {
const existing = result.filter((item) => item.type == object.type);
if (existing.length) {
const existingIndex = result.indexOf(existing[0]);
result[existingIndex].values = result[existingIndex].values.concat(object.values);
} else {
if (typeof object.values == 'string') object.values = [object.values];
result.push(object);
}
});
console.log(JSON.stringify(result));
Note:
If you want values to be an array of numbers instead of strings, just change the condition in line
15from'string'to'number'type.