我有两个对象:
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']
}
};
最后我需要合并这两个对象并得到类似的结果:
{
addedItems: [0, 1, 3, 4],
removedItems: [8, 9, 6, 7],
oneTwo: false,
someStuff: {
anotherArray: ['a', 'b', 'c', 'd']
}
}
应对具有不同结构的对象执行操作。
这样做的最佳方式(或可能的方式)是什么?在jQuery或下划线/ lodash中是否有任何允许这样做的方法?
答案 0 :(得分:4)
您是否检查了Lodash _.mergeWith(object, sources, customizer)
方法?我认为这个例子符合你的期望。
https://lodash.com/docs/4.17.4#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);
答案 1 :(得分:1)
您可以生成一个新对象,并使用已插入数组中的项附加数组。
function deepMerge(source, target) {
Object.keys(source).forEach(function (k) {
if (Array.isArray(source[k])) {
if (!Array.isArray(target[k])) {
target[k] = [];
}
target[k] = target[k].concat(source[k]);
return;
}
if (source[k] && typeof source[k] === 'object') {
target[k] = target[k] || {};
deepMerge(source[k], target[k]);
return;
}
target[k] = source[k];
});
}
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'] } },
result = {};
deepMerge(one, result);
deepMerge(two, result);
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }