我有2个阵列
var a = [{id: 1, name:"SFO"}, {id:2, name:"ATL"}];
var b = [{number: 1, sourceId:1, destinationId:2}, {number:2, sourceId:2, destinationId:1}];
我想以这种形式返回一个数组:
[{source: {name: "SFO"}, destination: {name: "ATL"}}, {source: {name:"ATL"}, destination: {name: "SFO"}}]
如何使用filter和reduce来生成上面的结果
答案 0 :(得分:1)
获得预期数组的代码:
var a = [{id: 1, name:"SFO"}, {id:2, name:"ATL"}];
var b = [{number: 1, sourceId:1, destinationId:2}, {number:2, sourceId:2, destinationId:1}];
var arr = [];
for(var i=0; i<b.length; i++){
arr.push({
source: {name: findName(b[i].sourceId, a) },
destination: {name: findName(b[i].destinationId, a) }
});
}
function findName(nr, a){
for(var i=0; i<a.length; i++){
if(nr==a[i].id){
return a[i].name;
}
}
}
//[{source: {name: "SFO"}, destination: {name: "ATL"}}, {source: {name:"ATL"}, destination: {name: "SFO"}}]
console.log(arr);
使用地图和过滤器获得预期的数组:
var a = [{id: 1, name:"SFO"}, {id:2, name:"ATL"}];
var b = [{number: 1, sourceId:1, destinationId:2}, {number:2, sourceId:2, destinationId:1}];
var arr = b.map(function(obj){
return {
source: { name: a.filter(function(obj2){ if(obj2.id==obj.sourceId) return obj2.name; })[0].name },
destination: { name: a.filter(function(obj2){ if(obj2.id==obj.destinationId) return obj2.name; })[0].name }
};
});
//[{source: {name: "SFO"}, destination: {name: "ATL"}}, {source: {name:"ATL"}, destination: {name: "SFO"}}]
console.log(arr);
答案 1 :(得分:0)
如果必须这样做,可以使用map()
和find()
,但效率非常低,您应该更改数据结构。
var a = [{id: 1, name:"SFO"}, {id:2, name:"ATL"}];
var b = [{number: 1, sourceId:1, destinationId:2}, {number:2, sourceId:2, destinationId:1}];
var result = a.map(function(e) {
var o = {}
o.source = {
name: e.name
}
var destB = b.find(function(f) {
return e.id == f.sourceId
})
if (destB) {
destB = destB.destinationId
var destName = a.find(function(x) {
return x.id == destB
})
if (destName) {
destName = destName.name;
o.destination = {
name: destName
}
}
}
return o
})
console.log(result)
&#13;