Skip to content

How to merge object arrays based on join of a key property in each

agershun edited this page Dec 28, 2014 · 2 revisions

How to merge object arrays based on join of a key property in each?

Source: StackOverflow.com

Question

How to merge the following object arrays, by first joining on the id property?

    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'
    }];

The result would be

    [{
        id: 1,
        name: 'fred',
        title: 'boss',
        wage: '300',
        rate: 'day'
    },{
        id: 2,
        name: 'jim',
        title: 'nobody',
        wage: '10',
        rate: 'hour'
    },{
        id: 3,
        name: 'bob',
        title: 'dancer',
        wage: '500',
        rate: 'week'
    }]

Answer

You can merge two arrays by id column with like in this example:

    var res = alasql('SELECT * FROM ? arr1 JOIN ? arr2 USING id', [arr1,arr2]);

Try this example at jsFiddle

Clone this wiki locally