下面我有两个JavaScript数组,它们都有相同数量的条目,但这个数字可能会有所不同。
[{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}]
[{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}]
我想将这两个数组合并,以便我得到
[{"5006":"GrooveToyota"},{"5007":"GrooveSubaru"},{"5008":"GrooveFord"}]
我不确定如何将其写入文字,但希望有人理解。我想用两个任意长度的数组(虽然长度相同)来做到这一点。
任何提示赞赏。
答案 0 :(得分:6)
这是一种拉链:
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;
}
答案 1 :(得分:3)
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"}]
答案 2 :(得分:0)
就我个人而言,我会以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;});
答案 3 :(得分:0)
类似于@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;});
合并; // [{5006:“GrooveToyota”},{5006:“GrooveSubaru”},{5006:“GrooveFord”}]
干杯!