2

I have 2 json objects in node.js

x= { '20': { length: '2', payload: [ '11', '22' ] } };
y= { '23': { length: '2', payload: [ 'ef', 'ab' ] } };

I want to combine them such that they become;

z= 
{
    '20': { length: '2', payload: [ '11', '22' ] },
    '23': { length: '2', payload: [ 'ef', 'ab' ] },
};

How can this be done in node.js?


EDIT: I found an easy answer myself. Cannot answer as question has been marked as duplicate.

Use underscore module.

var _under = require("underscore");

z= _under.extend(x, y);

1 Answers1

0

You can iterate over the keys and assign the properties to a new object.

var x = { '20': { length: '2', payload: ['11', '22'] } },
    y = { '23': { length: '2', payload: ['ef', 'ab'] } },

    object = function (x, y) {
        var r = {};
        function set(k) {
            r[k] = this[k];
        }
        Object.keys(x).forEach(set, x);
        Object.keys(y).forEach(set, y);
        return r;
    }(x, y)

document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392