根据键值组合数组中的对象

时间:2020-03-13 08:48:26

标签: javascript arrays lodash javascript-objects

我有一个带有公共密钥的对象数组。我想根据键值组合数组中的所有对象。

我的数组:

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

基于示例,我想基于常见的 day 键值合并数组中的对象,并合并其余的其他键值对(其余键是动态的。

预期输出:

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

我尝试使用Lodash和普通ES6,但仍然无法提出解决方案。

3 个答案:

答案 0 :(得分:1)

您可以使用lodash reduce函数,如下所示:

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;
} , []);

答案 1 :(得分:1)

尝试使用Array#reduceSpread Operator并使用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))

答案 2 :(得分:0)

找到了解决方案

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