代码之家  ›  专栏  ›  技术社区  ›  RGriffiths

推到数组中的数组上

  •  0
  • RGriffiths  · 技术社区  · 4 年前

    我有一个数组车辆,其中有一个数组内调用照片。例如:

    [
        {
            "id": 251,
            "make": "Toyota",
            "model": "Land Cruiser ",
            "photos": [
                {
                    "id": 7,
                    "photoUrl": "https://.../1607009083.jpg",
                }
            ]
        },
        {
            "id": 264,
            "make": "Toyota",
            "model": "Land Cruiser  II ",
            "photos": [
                {
                    "id": 9,
                    "photoUrl": "https://.../1607005508.jpg",
                }
            ]
        }
    ]
    

    this.vehicles[vehicleId].photos.push({id: photoId, photoUrl:  photoUrl}) 
    

    我哪里出错了?

    1 回复  |  直到 4 年前
        1
  •  1
  •   wangdev87    4 年前

    this.vehicles

    const index = this.vehicles.findIndex(v => v.id === vehicleId)
    if (index !== -1) {
      this.vehicles[index].photos.push({id: photoId, photoUrl:  photoUrl})
    } else {
      // No vehicle found with the vehicleId.
    }