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 giventype
property value already exists,concat()
- if an object with a giventype
already exists, the current objectvalues
are added to it usingconcat()
method.- additionally, we use
typeof
operator to check ifvalues
contain a single value and convert it to an array when necessary.
xxxxxxxxxx
1
const array = [
2
{ type: 1, values: 'a' },
3
{ type: 1, values: ['b', 'c'] },
4
{ type: 2, values: 'd' }
5
];
6
7
const result = [];
8
9
array.forEach((object) => {
10
const existing = result.filter((item) => item.type == object.type);
11
if (existing.length) {
12
const existingIndex = result.indexOf(existing[0]);
13
result[existingIndex].values = result[existingIndex].values.concat(object.values);
14
} else {
15
if (typeof object.values == 'string') object.values = [object.values];
16
result.push(object);
17
}
18
});
19
20
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
15
from'string'
to'number'
type.