我正在寻找一种更有效的方法来组合这三个数组。两个数据阵列和一个连接两个数组的“交叉”数组。
var drives = [
{"drivesId": "rwd", "name": "RWD"},
{"drivesId": "fwd", "name": "FWD"},
{"drivesId": "awd", "name": "AWD"}
]
var cars = [
{"carId": "civic", "name": "Civic"},
{"carId": "wrx", "name": "WRX"},
{"carId": "mustang", "name": "Mustang"},
{"carId": "focus", "name": "Focus"},
]
var drivesXcars = [
{"drivesXcars": "uid1", "carId": "civic", "drivesId": "fwd"},
{"drivesXcars": "uid2", "carId": "wrx", "drivesId": "awd"},
{"drivesXcars": "uid3", "carId": "mustang", "drivesId": "rwd"},
{"drivesXcars": "uid4", "carId": "focus", "drivesId": "fwd"},
]
我希望将它们组合成一个看起来像这样的数组:
var carsComplete = [
{"drivesId": "fwd", "driveName": "FWD", "cars": [
{"carId": "civic", "name": "Civic"},
{"carId": "focus", "name": "Focus"}
]},
{"drivesId": "rwd", "driveName": "RWD", "cars": [
{"carId": "mustang", "name": "Mustang"}
]},
{"drivesId": "awd", "driveName": "AWD", "cars": [
{"carId": "wrx", "name": "WRX"}
]},
]
是的,我可以做循环方式的标准,但是这些阵列变大了,标准的“暴力”方式对我来说还不够好。
我希望有人能够使用AngularJS和/或lodash知道更有效的方法。
答案 0 :(得分:3)
可以通过简单的JavaScript轻松实现:
const carsComplete = drives.map(x => ({
drivesId: x.drivesId,
driveName: x.name,
cars: drivesXcars
// Only the cars which belong to this person.
.filter(n => n.drivesId === x.drivesId)
// Get the car by id.
.map(n => cars.find(m => m.carId === n.carId))
}))
请参阅JS Bin。
答案 1 :(得分:0)
var drivesXcarsGroup = _.groupBy(drivesXcars, "drivesId");
var carsComplete = drives.map(function(driver){
return {
"drivesId": driver.drivesId,
"driveName": driver.name,
"cars": drivesXcarsGroup[driver.name.toLowerCase()]
}
});