0

I've got something like:

var object1 = { 'tab1' : [{ test : 10 }, { test : 15 }], 'tab2' : [{ test : 15 }] };

var object2 = { 'tab2' : [{ test : 35 }, { test : 25 }], 'tab3' : [{ test : 40 }] };

And I need the result:

var object3 = { 
    'tab1' : [{ test : 10 }, { test : 15 }],
    'tab2' : [{ test : 35 }, { test : 25 }, { test : 15 }],
    'tab3' : [[{ test : 40 }]
};

How can I do that?

$.extend(true, object1, object2) returns object without { test : 15 } in tab2

4
  • the order in tab2 is not random, first should be objects from tab2 object2 and than rest Commented Mar 15, 2013 at 17:36
  • 2
    @howderek he said what he tried: he tried a $.extend call which didn't give him test : 15 in teh results. Commented Mar 15, 2013 at 17:36
  • 3
    You're looking for a deep merge, which jQuery doesn't support. You'll have to do some sort of recursive merge. Commented Mar 15, 2013 at 17:37
  • @EliGassert thank you, I missed that. Commented Mar 15, 2013 at 18:03

1 Answer 1

2

I would just use javascript here, something like

var merged = [];
for (var key in object1) {
    if (object1.hasOwnProperty(key)){
       var obj1Arr, obj2Arr;
       obj1Arr = object1[key];
       obj2Arr = object2[key];

       if (obj1Arr) merged = merged.concat(obj1Arr);
       if (obj2Arr) merged = merged.concat(obj2Arr);
       object3[key] = merged;
        merged = [];
    }
}

for (var key in object2) {
    if (object2.hasOwnProperty(key) && !object3[key]){ // ignore the keys we already found
       var obj1Arr, obj2Arr;
       obj1Arr = object1[key];
       obj2Arr = object2[key];

       if (obj1Arr) merged = merged.concat(obj1Arr);
       if (obj2Arr) merged = merged.concat(obj2Arr);
       object3[key] = merged;
       merged = []; 
    }
}

console.log(object3) and a fiddle

http://jsfiddle.net/H4UGb/1/

you could clean this up a bit by putting the common code in the if statements into a function...

Sign up to request clarification or add additional context in comments.

2 Comments

almost great, but remember about that the order in tab2 is not random, first should be objects from tab2 object2 and than rest
then switch which array gets merged first

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.