-5

I have one object like this

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

and another object like this

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

The resultant object should look like this

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

The code is in a nodejs application. I am wondering if there is any javascript library to do this kind of merge/replace objects in server side js.

Thanks for helping.

Know Nothing
  • 1,121
  • 2
  • 10
  • 21

3 Answers3

1

There are quite a few npm packages out there to accomplish this, but one that is very popular is lodash.merge.

Take a look at the lodash merge function: 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.

And an example:

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 }] }

Use the lodash.merge npm package to pull in just this method: https://www.npmjs.com/package/lodash.merge

Good luck!

Flet
  • 439
  • 2
  • 2
  • An additional note about `Object.assign`: It will only copy the top level property values over, so it won't by default do the "deep merge" illustrated in the question. We would need to create a recursive function to iterate and `Object.assign` each property in order for it to work. Leaning on others code like `lodash.merge` is going to be more convenient and less prone to corner case errors since its well used. – Flet Jan 16 '18 at 18:37
0

This is what you want.

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);
Himanshu sharma
  • 7,487
  • 4
  • 42
  • 75
0

Try this:

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);
HOTAM SINGH
  • 121
  • 2
  • 11