Combine or merge JSON on node.js without jQuery

后端 未结 18 1999
醉话见心
醉话见心 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 17:48

    If using Node version >= 4, use Object.assign() (see Ricardo Nolde's answer).

    If using Node 0.x, there is the built in util._extend:

    var extend = require('util')._extend
    var o = extend({}, {name: "John"});
    extend(o,  {location: "San Jose"});
    

    It doesn't do a deep copy and only allows two arguments at a time, but is built in. I saw this mentioned on a question about cloning objects in node: https://stackoverflow.com/a/15040626.

    If you're concerned about using a "private" method, you could always proxy it:

    // myutil.js
    exports.extend = require('util')._extend;
    

    and replace it with your own implementation if it ever disappears. This is (approximately) their implementation:

    exports.extend = function(origin, add) {
        if (!add || (typeof add !== 'object' && add !== null)){
            return origin;
        }
    
        var keys = Object.keys(add);
        var i = keys.length;
        while(i--){
            origin[keys[i]] = add[keys[i]];
        }
        return origin;
    };
    

提交回复
热议问题