Combine or merge JSON on node.js without jQuery

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

    Underscore's extend is the easiest and quickest way to achieve this, like James commented.

    Here's an example using underscore:

    var _ = require('underscore'), // npm install underscore to install
      object1 = {name: "John"},
      object2 = {location: "San Jose"};
    
    var target = _.extend(object1, object2);
    

    object 1 will get the properties of object2 and be returned and assigned to target. You could do it like this as well, depending on whether you mind object1 being modified:

    var target = {};
    _.extend(target, object1, object2);
    

提交回复
热议问题