Combine or merge JSON on node.js without jQuery

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

    You should use "Object.assign()"

    There's no need to reinvent the wheel for such a simple use case of shallow merging.

    The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

    var o1 = { a: 1 };
    var o2 = { b: 2 };
    var o3 = { c: 3 };
    
    var obj = Object.assign(o1, o2, o3);
    console.log(obj); // { a: 1, b: 2, c: 3 }
    console.log(o1);  // { a: 1, b: 2, c: 3 }, target object itself is changed
    

    Even the folks from Node.js say so:

    _extend was never intended to be used outside of internal NodeJS modules. The community found and used it anyway. It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through Object.assign.


    Update:

    You could use the spread operator

    Since version 8.6, it's possible to natively use the spread operator in Node.js. Example below:

    let o1 = { a: 1 };
    let o2 = { b: 2 };
    let obj = { ...o1, ...o2 }; // { a: 1, b: 2 }
    

    Object.assign still works, though.


    PS1: If you are actually interested in deep merging (in which internal object data -- in any depth -- is recursively merged), you can use packages like deepmerge, assign-deep or lodash.merge, which are pretty small and simple to use.

    PS2: Keep in mind that Object.assign doesn't work with 0.X versions of Node.js. If you are working with one of those versions (you really shouldn't by now), you could use require("util")._extend as shown in the Node.js link above -- for more details, check tobymackenzie's answer to this same question.

提交回复
热议问题