Combine or merge JSON on node.js without jQuery

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

    Here is simple solution, to merge JSON. I did the following.

    • Convert each of the JSON to strings using JSON.stringify(object).
    • Concatenate all the JSON strings using + operator.
    • Replace the pattern /}{/g with ","
    • Parse the result string back to JSON object

      var object1 = {name: "John"};
      var object2 = {location: "San Jose"};
      var merged_object = JSON.parse((JSON.stringify(object1) + JSON.stringify(object2)).replace(/}{/g,","))
      

    The resulting merged JSON will be

    {name: "John", location: "San Jose"}
    
    0 讨论(0)
  • 2020-12-07 17:45

    If you need special behaviors like nested object extension or array replacement you can use Node.js's extendify.

    var extendify = require('extendify');
    
    _.extend = extendify({
        inPlace: false,
        arrays : 'replace',
        isDeep: true
    });
    
    obj1 = {
        a:{
            arr: [1,2]
        },
        b: 4
    };
    
    obj2 = {
        a:{
            arr: [3]
        }
    };
    
    res = _.extend(obj1,obj2);
    console.log(JSON.stringify(res)); //{'a':{'arr':[3]},'b':4}
    
    0 讨论(0)
  • 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;
    };
    
    0 讨论(0)
  • 2020-12-07 17:49

    Lodash is a another powerful tool-belt option for these sorts of utilities. See: _.merge() (which is recursive)

    var object = {
      'a': [{ 'b': 2 }, { 'd': 4 }]
    };
    var other = {
      'a': [{ 'c': 3 }, { 'e': 5 }]
    }; 
    _.merge(object, other);
    // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } 
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 17:54

    A better approach from the correct solution here in order to not alter target:

    function extend(){
      let sources = [].slice.call(arguments, 0), result = {};
      sources.forEach(function (source) {
        for (let prop in source) {
          result[prop] = source[prop];
        }
      });
      return result;
    }
    
    0 讨论(0)
提交回复
热议问题