简体   繁体   English

如何组合这两个JavaScript数组

[英]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. 我下面有两个JavaScript数组,它们都有相同数量的条目,但这个数字可能会有所不同。

[{"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) 示例(使用console.log即用户)

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 类似于@robert解决方案,但使用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; }); 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"}] // [{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: 就个人而言,我会以IAbstractDownvoteFactor的方式(+1),但对于另一个选项,我提出以下为您的编码乐趣:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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