samedi 9 juillet 2016

Merge not same length arrays of hashes based on key attribute

I would like to merge 2 arrays of hashes into 1 new array using JS, Underscore or JQuery.

Those 2 arrays could be different length and merge will be based on id attribute. Hashes in between same arrays may not have same id's , example:

arr1 id's = [1,5]

arr2 id's = [1,2]

Here are my arrays:

arr1 = [{
    id: 1
    name: 'fred'
},id: 5
    name: 'alex'
}];

arr2 = [{
    id: 1
    wage: '300'
},{
    id: 2
    wage: '10'
}]

so based on id attribute i should get following:

arr3 = [{
    id: 1
    name: 'fred'
    wage: '300'
},{
    id: 2
    wage: '10'
},{
    id: 5
    name: 'alex'
}]

I tried with Merging/extend javascript object arrays based on join of a key property in each but if arrays are not same length it doesn't work. Any help?

Aucun commentaire:

Enregistrer un commentaire