Search code examples
javascriptarrayslodashjavascript-objects

Combining objects in array based on key values


I have an array of objects with a common key. I would like to combine all the objects within the array based on key values.

My array:

let array = [
  {
    "day": "Monday",
    "item1": "abc"
  },
  {
    "day": "Tuesday",
    "item1": "def"
  },
  {
    "day": "Monday",
    "item2": "123"
  },
  {
    "day": "Tuesday",
    "item2": "456"
  }
]

Based on the example, I want to combine the objects within my array based on the common day key values and merge the rest of the other key value pairs (the rest of the keys are dynamic).

Expected output:

[
  {
    "day": "Monday",
    "item1": "abc",
    "item2": "123"
  },
  {
    "day": "Tuesday",
    "item1": "def",
    "item2": "456"
  }
]

I have tried using Lodash and plain ES6 but still unable to come up with a solution for it.


Solution

  • You can use lodash reduce function, like this:

    let array = [
      {
        "day": "Monday",
        "item1": "abc"
      },
      {
        "day": "Tuesday",
        "item1": "def"
      },
      {
        "day": "Monday",
        "item2": "123"
      },
      {
        "day": "Tuesday",
        "item2": "456"
      }
    ]
    
    let merged = _.reduce(array, function(result, value, key) {
    
      let item = result.find(item => item.day === value.day);
    
      if (!item) {
        result.push(value)
      } else {
         _.merge(item, value);
      }
    
      return result;
    } , []);