javascript combine object with same key

Combining objects with same key in JavaScript

Have you ever faced a situation where you have multiple objects with the same key and you want to combine them into a single object? If yes, then you have landed on the right page. In this post, I will explain how to combine objects with the same key in JavaScript.

Method 1: Using reduce method

The reduce method is used to reduce an array to a single value. In this case, we will use it to combine objects with the same key. Here's how we can do it:


const data = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'John', city: 'New York' },
  { name: 'Jane', city: 'San Francisco' }
];

const result = data.reduce((acc, obj) => {
  const key = obj.name;
  if (!acc[key]) {
    acc[key] = {};
  }
  Object.assign(acc[key], obj);
  return acc;
}, {});

console.log(result);

In this code, we first define an array of objects with the same key. Then we use the reduce method on this array to combine the objects. We create an empty object as the initial value for the accumulator. We then iterate over each object in the array and check if the accumulator object has a property with the same key as the current object. If not, we create a new property with that key and assign an empty object as its value. We then use Object.assign method to merge the current object into the accumulator object's property with the same key. Finally, we return the accumulator object.

Method 2: Using lodash library

If you are not familiar with the reduce method, you can use the lodash library which provides a mergeWith method to combine objects with the same key. Here's how we can do it:


const _ = require('lodash');

const data = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'John', city: 'New York' },
  { name: 'Jane', city: 'San Francisco' }
];

const result = _.mergeWith({}, ...data, (objValue, srcValue) => {
  if (_.isObject(objValue)) {
    return _.merge(objValue, srcValue);
  }
});

console.log(result);

In this code, we first import the lodash library. We then define an array of objects with the same key. We create an empty object as the initial value for the mergeWith method. We then pass the spread operator to unpack the array and pass each object as a separate argument. We then define a customizer function which is called for each property that is being merged. If the property is an object, we use the merge method of lodash to recursively merge its properties. Finally, we return the merged value.

Conclusion

So these were two methods to combine objects with the same key in JavaScript. You can use any of these methods based on your preference and familiarity with the reduce method or the lodash library.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe