combine 2 arrays of objects on id.

by KooiInc MeHere

HTML

<script src="http://www.nicon.nl/genericsvc/helpers.js"></script>

CSS

body {font:0.8em verdana,arial}

JavaScript

var arr1 = [{
    id: 1,
    name: 'fred',
    title: 'boss'
},{
    id: 2,
    name: 'jim',
    title: 'nobody'
},{
    id: 3,
    name: 'bob',
    title: 'dancer'
}];

var arr2 = [{
    id: 1,
    wage: '300',
    rate: 'day'
},{
    id: 2,
    wage: '10',
    rate: 'hour'
},{
    id: 3,
    wage: '500',
    rate: 'week'
}];

alert = $H.displayln;

alert('simple merge (arr1 is the merged result)','---');
merge(arr1,arr2);
for (var i=0;i<arr1.length;i++){
    var r = [];
    for (var l in arr1[i]){
        if (arr1[i].hasOwnProperty(l)){
         r.push(l+': '+arr1[i][l]);
        }
    }
    alert(r.join('<br />')+'<br />');
}

alert('combineArraysOnId (destroys arr1)','---');
var combine = combineArraysOnId(arr1,arr2);
for (var i=0;i<combine.length;i++){
    var r = [];
    for (var l in combine[i]){
        if (combine[i].hasOwnProperty(l)){
         r.push(l+': '+combine[i][l]);
        }
    }
    alert(r.join('<br />')+'<br />');
}


function combineArraysOnId(arr1,arr2){
 var combined = [];
 function findSecond(id,second) {
    for (var i=0;i<second.length;i++){
        if(second[i].id === id){
            return second[i];
        }
    }
    return null
 }

 while (el = arr1.pop()){
    var getSec = findSecond(el.id,arr2);
    if (getSec){
        for (var l in getSec){
            if (!(l in el)) {
                el[l] = getSec[l];
            }
        }
        combined.push(el);
    }
 }
 //reverse the array, because we popped the objects
 return combined.reverse();
 }


//If arrays have the same length, and the id's are equal, things are easier:
function merge(a1,a2) {
    var i = -1;
    while ((i = i+1)<a1.length)  {
     for (var l in a2[i]) {
            if (!(l in a1[i] )) {
                a1[i][l] = a2[i][l];
            }
     }
    }
   return a1; 
}