Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine these two JavaScript arrays

I have two JavaScript arrays below that both have the same number of entries, but that number can vary.

[{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}]      
[{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}] 

I want to combine these two arrays so that I get

[{"5006":"GrooveToyota"},{"5007":"GrooveSubaru"},{"5008":"GrooveFord"}]

I'm not sure how to put it into words but hopefully someone understands. I would like to do this with two arrays of arbitrary length (both the same length though).

Any tips appreciated.

like image 837
Hard worker Avatar asked Jul 07 '26 05:07

Hard worker


1 Answers

It's kind of a zip:

function zip(a, b) {
    var len = Math.min(a.length, b.length),
        zipped = [],
        i, obj;
    for (i = 0; i < len; i++) {
        obj= {};
        obj[a[i].branchids] = b[i].branchnames;
        zipped.push(obj);
    }
    return zipped;
}

Example (uses console.log ie users)

like image 157
Joe Avatar answered Jul 08 '26 19:07

Joe