lodash - 如何合并相同的对象并将它们的原始值推送到相应的数组中

lodash - how to merge identical object and pushes their primitive value into the respective array

我有一组像这样的相同对象。我想将它们合并到一个对象中,因为只有原始值 "stacked" 到一个数组中,而对象将被遍历并且数组将被连接起来。

我更喜欢功能性解决方案(我可以很好地处理 for 循环,...)

const x = [
  {
    a: 1,
    b: 'hi',
    c: { d: 1 },
    e:[1,2]
  },
  {
    a: 2,
    b: 'there',
    c: { d: 2 },
    e:[3,4]
  }
];

const result = {
  a:[1,2],
  b:['hi','there'],
  c:{
    d:[1,2]
  },
  e:[1,2,3,4]
}

无论如何提示 use/chain 的 lodash 方法足以让我弄清楚这个问题。目前我被卡住了...

_.mergeWith() 与自定义程序方法结合使用来处理数组连接和原语。由于 _.mergeWith() 是递归的,它将处理嵌套对象。

const x = [{"a":1,"b":"hi","c":{"d":1},"e":[1,2]},{"a":2,"b":"there","c":{"d":2},"e":[3,4]}];

const result = _.mergeWith({}, ...x, (ov, sv) => {
  if(Array.isArray(ov)) return ov.concat(sv);
  
  if(ov !== undefined && !_.isObject(ov)) return [ov, sv];
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>