我正在寻找一种更有效的方法来组合这三个数组。两个数据数组和一个连接这两个数组的“交叉”数组。
3个数组
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"}
]},
]
是的,我可以用标准的 for 循环方式来做到这一点,但是这些数组变得越来越大,标准的“强力”方式对我来说不够好。
我希望有人会知道使用 AngularJS 和/或 lodash 执行此操作的更有效方法。
最佳答案
它可以用普通的 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 .
关于javascript - 将三个数组合二为一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35801763/