简体   繁体   中英

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.

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)

var ids = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}];
var names = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}];
var combined = [];

for (var i = 0; i < ids.length; i++) {
    var combinedObject = {};
    combinedObject[ids[i].branchids] = names[i].branchnames;
    combined.push(combinedObject);
}

combined; // [{"5006":"GrooveToyota"},{"5006":"GrooveSubaru"},{"5006":"GrooveFord"}]

similar to @robert solution but using Array.prototype.map

var ids = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}], names = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}], merged = ids.map(function (o, i) { var obj = {}; obj[o.branchids]=names[i].branchnames; return obj; });

merged; //[{5006: "GrooveToyota"}, {5006: "GrooveSubaru"}, {5006:"GrooveFord"}]

Cheers!

Personally, I would do it IAbstractDownvoteFactor's way (+1), but for another option, I present the following for your coding pleasure:

var a = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}];
var b = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}];
var zipped = a.map(function(o,i){ var n={};n[o.branchids]=b[i].branchnames;return n;});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM