0

I'm trying to merge/concat 2 objects, such a way that currently i have:

var mergeObj = {};
var obj1 = { name: 'abd', id: 5454756, color: 'red' }
var obj2 = { name: 'abc1', id:387589, color: 'blue'}

Now if I merge it should be:

Object {obj1: Object, obj2: Object}

However I tried the following:

mergeObj = obj1.merge(obj2);

and it merges to one object, which is not what i'm looking for. I want to merge in such a way that the final object will have 2 fields: obj1 and obj2.

Ex:

enter image description here

is it possible?? Any ideas?

thanks~

Community
  • 1
  • 1
user1234
  • 3,000
  • 4
  • 50
  • 102

5 Answers5

2
var obj1 = { name: 'abd', id: 5454756, color: 'red' }
var obj2 = { name: 'abc1', id:387589, color: 'blue'}
var mergeObj = { obj1: obj1, obj2: obj2 };

In javascript everything is an object and a property can be any object, so you just need to create a new object with the properties of it set to the original objects.

Gabriel Sadaka
  • 1,748
  • 1
  • 15
  • 19
1

try this,

$(document).ready(function() {
  var obj1 = {
    name1: 'abd',
    id: 5454756,
    color: 'red'
  }
  var obj2 = {
    name: 'abc1',
    id: 387589,
    color: 'blue'
  }

  $.extend(obj1, obj2);
  alert(obj2.name + "," + obj1.name);

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
user786
  • 3,902
  • 4
  • 40
  • 72
1

Since there's only two objects, you could quite simply add them together as a new object.

var obj1 = { name: 'abd', id: 5454756, color: 'red' },
    obj2 = { name: 'abc1', id:387589, color: 'blue'},
    objs = { obj1, obj2 };

console.log(obj1, obj2, objs);

// Output:
// Object {name: "abd", id: 5454756, color: "red"}
// Object {name: "abc1", id: 387589, color: "blue"}
// Object {obj1: Object, obj2: Object}

http://jsfiddle.net/daCrosby/o7jf5baa/

You can do it with more than two, I just mean it's simple enough without any complex functions or extra libraries.

DACrosby
  • 11,116
  • 3
  • 39
  • 51
0

This question appears to be a duplicate of jquery merge two objects.

The solution provided by adeneo is:

//merging two objects into new object
var new_object = $.extend({}, object1, object2);
Community
  • 1
  • 1
Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62
0

have a look at this code

var mergeObj = {};

var obj1 = { name: 'abd', id: 5454756, color: 'red' }
var obj2 = { name: 'abc1', id:387589, color: 'blue'}


mergeObj.obj1=obj1;
mergeObj.obj2=obj2;
console.log(mergeObj)
shreyansh
  • 1,637
  • 4
  • 26
  • 46