0

I have two JavaScript objects with the structure below.

var obj1  = {id1: 10, name1: "stack"};
var obj2  = {id2: 20, name2: "overflow"};

I want to concat them together as a single object (not array) using Javascript.

The result should be like this.

var res = {id: 10, name1: "stack", id2: 20, name2: "overflow"};

Is there an easy way to do this using pure javascript?

Note: I don't need jQuery to do this and I want to concat is for json objects, not as json arrays using concat method. Is there any simple method or way to achieve this?

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
UI_Dev
  • 3,317
  • 16
  • 46
  • 92
  • 1
    In ES6 you can use `Object.assign`. For example: `Object.assign({}, obj1, obj2)` – Dmitriy Mar 08 '16 at 14:28
  • 1
    Language lawyer alert, those are actually object literals. Yes they can be JSON but the key difference is JSON keys must be strings. – Phil Cooper Mar 08 '16 at 14:32
  • Put it another way: There is no JSON in this question. JSON is a textual notation for data exchange. If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Mar 08 '16 at 14:33

2 Answers2

3

Use Object.assign

var obj1 = {a: 1}, obj2 = {b:2}
// Using three arguments so that obj 1 and 2 aren't modified
var result = Object.assign({}, obj1, obj2);
// result.a -> 1
// result.b -> 2
// obj1.b -> undefined
// obj2.a -> undefined

// You could modify obj1
Object.assign(obj1, obj2);
// obj1.b -> 2

Polyfill:

if (typeof Object.assign != 'function') {
  (function () {
    Object.assign = function (target) {
      'use strict';
      if (target === undefined || target === null) {
        throw new TypeError('Cannot convert undefined or null to object');
      }

      var output = Object(target);
      for (var index = 1; index < arguments.length; index++) {
        var source = arguments[index];
        if (source !== undefined && source !== null) {
          for (var nextKey in source) {
            if (source.hasOwnProperty(nextKey)) {
              output[nextKey] = source[nextKey];
            }
          }
        }
      }
      return output;
    };
  })();
}
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
0

A simple plain solution:

function addToObject(source, target) {
    Object.keys(source).forEach(function (k) {
        target[k] = source[k];
    });
}

var obj1 = { id1: 10, name1: "stack" },
    obj2 = { id2: 20, name2: "overflow" },
    result = {};

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