Combine or merge JSON on node.js without jQuery

后端 未结 18 2012
醉话见心
醉话见心 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:52

    A normal loop?

    function extend(target) {
        var sources = [].slice.call(arguments, 1);
        sources.forEach(function (source) {
            for (var prop in source) {
                target[prop] = source[prop];
            }
        });
        return target;
    }
    
    var object3 = extend({}, object1, object2);
    

    That's a basic starting point. You may want to add things like a hasOwnProperty check, or add some logic to handle the case where multiple source objects have a property with the same identifier.

    Here's a working example.

    Side note: what you are referring to as "JSON" are actually normal JavaScript objects. JSON is simply a text format that shares some syntax with JavaScript.

提交回复
热议问题