How can I merge jquery objects together
I have
{
\"merchantcontract\":\"Ready Reserve Foods 10104.01\",
\"merchantcontractid\":\"c4253769-5a57-e11
If you want to update your existing object, use:
$.extend(obj1, obj2); //update obj1 and put all obj2 values in it.
$.extend will change the values of your existing object
To create a new third object that is the sum of both objects, you can use this function
function merger_objects(obj1,obj2){
$.each(obj2, function(key, value) {
obj1[key] = value;
});
return obj1;
}
Example
var fruit = {apple:"sweet",graps:"bitter"}
var vege = {cucamber:"bitter",letuce:"bitter"}
var fruit_and_vege = merger_objects(fruit,vege);
//returns {apple:"sweet",graps:"bitter",cucamber:"bitter",letuce:"bitter"}
can you put them in an array?
var myObjects = [];
and in your each where they are created just add:
myObjects.push(newObject);
jQuery's $.extend will do what you want.
//merging two objects into new object
var new_object = $.extend({}, object1, object2);
//merge object2 into object1
$.extend(object1, object2);
In case you wish to merge them recursively, $.extend offers the argument deep
. In case deep=true
the merge become recursively. An example above,
// Initialize two objects.
var json1 = { "a": { "a1": "value1", "a2": "value2" }};
var json2 = { "a": { "a3": "value3" }};
// Merge them recursively.
var newJson = $.extend(true, {}, json1, json2);
// Test it.
if (newJson.a.a1 && newJson.a.a3) {
console.log("Success");
}
anObj={'propone':'1', 'proptwo':'2'};
anotherObj={'propel':'11', 'proptlv':'12'};
var opts = {};
$.extend(opts, anObj, anotherObj, {
bar: "baz",
thing: "foo"
});
console.log(opts);
Example