-2

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.

0

3 Answers 3

1

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;
} , []);
Sign up to request clarification or add additional context in comments.

Comments

1

Try using Array#reduce , Spread Operator and approach with ES6

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

let res =  arr.reduce((acc,{day,...rem})=>( acc[day]  = acc[day] ? {...acc[day],...rem} : {day,...rem},acc),{});

console.log(Object.values(res))

Comments

0

Found the solution

_(array).groupBy('day').map(_.spread(_.assign)).value()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.