2

I have

object1 = {"abc":{"name":"myabcname"}}
object2 = {"def":{"name":"defname"}}

I want to form a object/string as i.e. as comma seperated of both object values.

{"abc":{"name":"myabcname"},"def":{"name":"defname"}};

when i try doing console.log(JSON.stringify(object1)+JSON.stringify(object2)) it prints like this {"abc":{"name":"myabcname"}}{"def":{"name":"defname"}}

LarsW
  • 1,514
  • 1
  • 13
  • 25
krish
  • 469
  • 1
  • 15
  • 34
  • Possible duplicate of [How can I merge properties of two JavaScript objects dynamically?](https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – adeneo Jul 20 '17 at 21:31

7 Answers7

4

You can use Object.assign to achieve this:

var object1 = {"abc":{"name":"myabcname"}};
var object2 = {"def":{"name":"defname"}};

var mergedObject = Object.assign({}, object1, object2);

console.log(mergedObject);
Alberto Trindade Tavares
  • 10,056
  • 5
  • 38
  • 46
  • Dont know whats wrong going here with this code `var object1 = {"abc":{"name":"myabcname"}}; console.log("object1"+object1); var object2 = {"def":{"name":"defname"}}; console.log("object2"+object2); var mergedObject = Object.assign({}, object1, object2); console.log("mergedObject"+mergedObject);` It shows as below in the chrome browser console log. `object1[object Object] object2[object Object] mergedObject[object Object]` – krish Jul 20 '17 at 22:08
  • @krish The idea of `Object.assign` here is merge the second and third parameters (object1 and object2) and copy the result to the first parameter (an empty object), and this resulting object is returned. So you have the merge of object1 and object2 into a new object – Alberto Trindade Tavares Jul 20 '17 at 22:10
  • @krish you can't concatenate objects like that, and there is no need for trying this, because `mergedObject` is already the result you want! – Alberto Trindade Tavares Jul 20 '17 at 22:11
  • Yes when i try to print the merged object `var mergedObject = Object.assign({}, object1, object2); console.log("mergedObject"+mergedObject);` it shows me as `mergedObject[object Object]` as i need to take that merged string to pass as a request parameter to a GET request Ajax call. – krish Jul 20 '17 at 22:16
  • @krish If you want to print a textual version of the object concatenated to a string in that way, use `JSON.stringify`: `console.log("mergedObject: " + JSON.stringify(mergedObject))`; – Alberto Trindade Tavares Jul 20 '17 at 22:20
1

You can use jquery $.extend.

//merging two objects & create new one
var new_object = $.extend({}, object1, object2);


//Merge object2 into object1, recursively
$.extend( true, object1, object2 );
Omi
  • 3,954
  • 5
  • 21
  • 41
0

If you're using jquery, you can $.extend the first object into the second.

catbadger
  • 1,662
  • 2
  • 18
  • 27
0

JQuery .extend() will merge two objects into a third if specified (in addition to @Alberto's answer)

// from jQuery docs
var object1 = {
  apple: 0,
  banana: { weight: 52, price: 100 },
  cherry: 97
};
var object2 = {
  banana: { price: 200 },
  durian: 100
}

var object3 = {};

$.extend(object3, object1, object2 );

console.log(object3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
wahwahwah
  • 3,254
  • 1
  • 21
  • 40
0

You can make it like this :

object1 = {"abc":{"name":"myabcname"}}
object2 = {"def":{"name":"defname"}}
obj = []
obj[Object.keys(object1)[0]] = object1
obj[Object.keys(object2)[0]] = object2
Benjamin Audet
  • 463
  • 3
  • 12
0

You can use Object.assign to achieve this, but if you want to support "Internet Explorer" (IE8, IE9, IE10 and IE11) you will need to use this Polyfill:

if (typeof Object.assign != 'function') {
  Object.assign = function(target, varArgs) { // .length of function is 2
    'use strict';
    if (target == null) { // TypeError if undefined or null
      throw new TypeError('Cannot convert undefined or null to object');
    }

    var to = Object(target);

    for (var index = 1; index < arguments.length; index++) {
      var nextSource = arguments[index];

      if (nextSource != null) { // Skip over if undefined or null
        for (var nextKey in nextSource) {
          // Avoid bugs when hasOwnProperty is shadowed
          if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
    }
    return to;
  };
}

Reference: MDN

Use:

var obj1 = {"abc":{"name":"myabcname"}};
var obj2 = {"def":{"name":"defname"}};

var mergedObj = Object.assign({}, obj1, obj2);

console.log(mergedObj);
sidanmor
  • 5,079
  • 3
  • 23
  • 31
0

In order to achieve a string in form that you presented you can use:

var object1 = {"abc":{"name":"myabcname"}};
var object2 = {"def":{"name":"defname"}};
var myObject = Object.assing({}, object1, object2);
var myString = JSON.stringify(myObject);
// "{"abc":{"name":"myabcname"},"def":{"name":"defname"}}"

Danger of using Object.assign - It is only one level deep copy. Example:

var me = {
  name: "Tomasz",
  lastName: "Bubała",
  social: {
    github: "@tomegz",
    twitter: "@tomaszbubala"
  }
};

var dev = Object.assign({}, me);
/* This is fine */
dev.name = "Tom";
// => "Tom"
me.name;
// => "Tomasz"
/* This is danger */
dev.social.twitter = "@example";
// => "@example"
me.social.twitter;
// => "@example"

Hopefully in ES7 you will be able to use spread operator to achieve this effecft:

var myObject = {...object1, ...object2};
Tomasz Bubała
  • 2,093
  • 1
  • 11
  • 18