Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将三个阵列合并为一个阵列_Javascript_Arrays_Angularjs_Lodash - Fatal编程技术网

Javascript 将三个阵列合并为一个阵列

Javascript 将三个阵列合并为一个阵列,javascript,arrays,angularjs,lodash,Javascript,Arrays,Angularjs,Lodash,我正在寻找一种更有效的方法来组合这三个阵列。两个数据阵列和一个连接两个阵列的“交叉”阵列 3阵列 我希望将它们组合成一个数组,如下所示: var carsComplete = [ {"drivesId": "fwd", "driveName": "FWD", "cars": [ {"carId": "civic", "name": "Civic"}, {"carId": "focus", "name": "Focus"} ]}, {"dri

我正在寻找一种更有效的方法来组合这三个阵列。两个数据阵列和一个连接两个阵列的“交叉”阵列

3阵列 我希望将它们组合成一个数组,如下所示:

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实现这一点的更有效的方法。

这可以通过简单的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))
}))
请参阅。

使用


你不需要太多的暴力,这取决于你如何编码。我会首先将驱动器和汽车转换成一个由有趣的道具设置关键帧的对象,然后简单地迭代drivesXcars并将它们像
obCars[x.carId]
一样混合在一起,而不是一些愚蠢/缓慢的
indexOf()
疯狂。。。
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))
}))
var drivesXcarsGroup = _.groupBy(drivesXcars, "drivesId");
var carsComplete = drives.map(function(driver){
                            return {
                                "drivesId": driver.drivesId,
                                "driveName": driver.name,
                                "cars": drivesXcarsGroup[driver.name.toLowerCase()]
                               }
                           });