如何在JavaScript中将两个对象与数组属性连接在一起?

Vov*_*vch 1 javascript jquery underscore.js lodash

我有两个对象:

var one = {
  addedItems: [0, 1],
  removedItems: [8, 9],
  oneTwo: false,
  someStuff: {
    anotherArray: ['a', 'b']
  }
};

var two = {
  addedItems: [3, 4],
  removedItems: [6, 7],
  someStuff: {
    anotherArray: ['c', 'd']
  }
};
Run Code Online (Sandbox Code Playgroud)

最后,我需要合并这两个对象并获得如下内容:

{
  addedItems: [0, 1, 3, 4],
  removedItems: [8, 9, 6, 7],
  oneTwo: false,
  someStuff: {
    anotherArray: ['a', 'b', 'c', 'd']
  }
}
Run Code Online (Sandbox Code Playgroud)

操作时应在具有不同结构的对象来执行。

什么是做到这一点的最佳方式(或者只是可能的方式)?是否有jQuery中或下划线/ lodash允许这样做的任何方法?

Nic*_*lle 5

您检查过Lodash _.mergeWith(object, sources, customizer)方法吗?我认为该示例符合您的基本期望。

https://lodash.com/docs/4.17.15#mergeWith

var one = { addedItems: [0, 1], removedItems: [8, 9], oneTwo: false, someStuff: { anotherArray: ['a', 'b'] } },
    two = { addedItems: [3, 4], removedItems: [6, 7], someStuff: { anotherArray: ['c', 'd'] } };

// In case of arrays, concatenate them instead
function customizer(objValue, srcValue) {
  if (_.isArray(objValue)) {
    return objValue.concat(srcValue);
  }
}

var result = _.mergeWith(one, two, customizer);
Run Code Online (Sandbox Code Playgroud)

这是小提琴中的工作示例