Reputation: 3159
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:
is it possible?? Any ideas?
thanks~
Upvotes: 0
Views: 50
Reputation: 6852
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);
Upvotes: 0
Reputation: 1687
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)
Upvotes: 0
Reputation: 11450
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.
Upvotes: 1
Reputation: 4364
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>
Upvotes: 1
Reputation: 1746
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.
Upvotes: 2