开发者

How to combine these two JavaScript arrays

开发者 https://www.devze.com 2023-04-12 18:31 出处:网络
I have two JavaScript arrays below that both have the same number of entries, but that number can vary.

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 开发者_StackOverflow中文版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"}]


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;});


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号