Combine or merge JSON on node.js without jQuery

后端 未结 18 1963
醉话见心
醉话见心 2020-12-07 17:17

I have multiple JSON like those

var object1 = {name: \"John\"};
var object2 = {location: \"San Jose\"};

They are not nesting o

18条回答
  •  醉梦人生
    2020-12-07 18:04

    You can also use this lightweight npm package called absorb

    It is 27 lines of code, 1kb and uses recursion to perform deep object merges.

    var absorb = require('absorb');
    var obj1, obj2;
    
    obj1 = { foo: 123, bar: 456 };
    obj2 = { bar: 123, key: 'value' }
    
    absorb(obj1, obj2);
    
    console.log(obj1); // Output: { foo: 123, bar: 123, key: 'value' }
    

    You can also use it to make a clone or only transfer values if they don't exist in the source object, how to do this is detailed in the link provided.

提交回复
热议问题