Languages
[Edit]
EN

JavaScript - merge objects in array with the same keys

0 points
Created by:
cory
1756

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:

  1. forEach() - to iterate over all objects inside array,
  2. filter() - to check if an object with a given type property value already exists,
  3. concat() - if an object with a given type already exists, the current object values are added to it using concat() method.
  4. additionally, we use typeof operator to check if values contain a single value and convert it to an array when necessary.

Practical example

Edit

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.

 

See also

Edit
  1. JavaScript - group / grouping array items with reduce method

References

Edit
  1. Array.prototype.forEach() - JavaScript | MDN
  2. Array.prototype.filter() - JavaScript | MDN
  3. Array.prototype.indexOf() - JavaScript | MDN
  4. Array.prototype.concat() - JavaScript | MDN

Alternative titles

  1. JavaScript - merge associative array of objects with the same keys
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join