-2

I have two JavaScript objects

a =  {"aa" : "foo"}
b = {"b" : "bar"}

I want to concat both and want to get this result

result =  {"aa" : "foo" , "b" :"bar"}

what is the simplest way to do this in plain javascript. I am not using any external libraries like jquery or underscore.

Liam
  • 27,717
  • 28
  • 128
  • 190
Ashisha Nautiyal
  • 1,389
  • 2
  • 19
  • 39

3 Answers3

3

Use Object.assign, here is the documentation.

var mergedObject = Object.assign(a, b);

Be aware that Object.assign will merge from left to right so any keys that are the same will be overridden if added later in the parameter list.

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
2
var o1 = {"aa" : "foo" };
var o2 = { "b" : "bar" };

var obj = Object.assign(o1, o2);
Gayathri Mohan
  • 2,924
  • 4
  • 19
  • 25
2

Ideally, as suggested in the previous two answers, using Object.assign is your best bet, unless browser support dictates otherwise, although, the MDN documentation provides an ES5 polyfill.

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

    target = Object(target);
    for (var index = 1; index < arguments.length; index++) {
      var source = arguments[index];
      if (source != null) {
        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
    }
    return target;
  };
}
connorb
  • 301
  • 4
  • 16
Ramcharan Reddy
  • 621
  • 1
  • 5
  • 18