0

I have three objects in two arrays:

var tab1 = [{"foo":"bar"}, {"foo2":"bar2"}, {"foo3":"bar3"} ];

var tab2 = [ {"2foo":"2bar"}, {"2foo2":"2bar2"}, {"2foo3":"2bar3"} ];

My goal is merge that arrays like this:

 var tab3 = [ {"foo":"bar", "2foo":"2bar"},  {"foo2":"bar2",
 "2foo2":"2bar2"},  {"foo3":"bar3", "2foo3":"2bar3"}  ];

How can I do this?

PSL
  • 123,204
  • 21
  • 253
  • 243
Siper
  • 1,175
  • 1
  • 14
  • 39

4 Answers4

3

If you're using jQuery, you can use jQuery.extend().

It does exactly what you want.

Example:

for (var i = 0; i < tab1.length; i++) {
    tab1[i] = $.extend(tab1[i], tab2[i]);
}

Here's a fiddle: http://jsfiddle.net/fCx9C/2/

If you don't want to use jQuery, you can see how they implement jQuery.extend() here.

If you do want to use jQuery, here's the jQuerified loop:

$.each(tab1, function (i, t) {
    t = $.extend(t, tab2[i]);
});
jahroy
  • 22,322
  • 9
  • 59
  • 108
1

Demo

function merge(obj1, obj2) {
    var tmp = {};
    for (var key in obj1) {
        tmp[key] = obj1[key];
    };
    for (key in obj2) {
        tmp[key] = obj2[key];
    };
    return tmp;
};

function zip(arr1, arr2) {
    var tmp = [];
    for (var i = 0, len = arr1.length; i < len; i++) {
        tmp[i] = merge(arr1[i], arr2[i]);
    };
    return tmp;
};

var tab1 = [{"foo":"bar"}, {"foo2":"bar2"}, {"foo3":"bar3"} ];

var tab2 = [ {"2foo":"2bar"}, {"2foo2":"2bar2"}, {"2foo3":"2bar3"} ];

console.log(zip(tab1, tab2));
flavian
  • 28,161
  • 11
  • 65
  • 105
0

This should do what you want:

var merge = function(t1, t2) { 
    var arr = []; 
    for(i=0; i<t1.length; i++) { 
        for(var prop in t2[i]) { 
            arr.push(t1[i]); 
            arr[i][prop] = t2[i][prop]; 
        } 
    } 
    return arr; 
}

var tab3 = merge(tab1, tab2);
Seiyria
  • 2,112
  • 3
  • 25
  • 51
  • You're right, it does. Though, I wasn't sure how transient the variables would be and if merging was okay. If merging isn't okay - flavs solution is the one to go with. – Seiyria Jun 13 '13 at 19:15
0

This can be done in vanilla JavaScript quite nicely:

var tab1 = [{"foo":"bar"}, {"foo2":"bar2"}, {"foo3":"bar3"} ];
var tab2 = [ {"2foo":"2bar"}, {"2foo2":"2bar2"}, {"2foo3":"2bar3"} ];
var tab3 = [];
for(var i = 0; i < 3; i++) {
    for(var j in tab2[i]) {
        tab1[i][j] = tab2[i][j];
    }
    tab3.push(tab1[i]);
}
console.log(tab3);

However, you don't even have to create a tab3 array as it puts everything nicely into tab1 already.

faino
  • 3,194
  • 15
  • 17