如何合并两个 javascript 对象

How do you merge two javascript objects

我有一个这样的对象

let ob1 = {
'item_data':{
  'stack':{
    'purchase':'12345',
    'order':'22222'
   }
  }
}

还有一个像这样的对象

let ob2 = {
  'stack':{
    'purchase':'444444'
   }
 }

生成的对象应如下所示

result = {
  'item_data':{
    'stack':{
      'purchase':'444444',
      'order':'22222'
     }
   }
 }

代码在 nodejs 应用程序中。我想知道是否有任何 javascript 库可以在服务器端 js 中执行这种 merge/replace 对象。

感谢您的帮助。

这就是你想要的。

let ob1 = {
'item_data':{
  'stack':{
    'purchase':'12345',
    'order':'22222'
   }
  }
}
// and another object like this

let ob2 = {
  'stack':{
    'purchase':'444444'
   }
 }
Object.assign(ob1.item_data.stack, ob2.stack);
console.log(ob1);

试试这个:

function merge(a, b) {
    for (var key in b) {
        if (exports.merge.call(b, key) && b[key]) {
            if ('object' === typeof (b[key])) {
                if ('undefined' === typeof (a[key])) a[key] = {};
                exports.merge(a[key], b[key]);
            } else {
                a[key] = b[key];
            }
        }
    }
    return a;
}
merge(obj1, obj2);

有很多 npm 包可以实现这一点,但最流行的是 lodash.merge

看看lodash的合并函数: https://lodash.com/docs/4.17.4#merge

This method is like _.assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.

还有一个例子:

var object = {
  'a': [{ 'b': 2 }, { 'd': 4 }]
};
var other = {
  'a': [{ 'c': 3 }, { 'e': 5 }]
};

_.merge(object, other);
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }

使用 lodash.merge npm 包来引入这个方法: https://www.npmjs.com/package/lodash.merge

祝你好运!