-1

I hava an array vehicles which has an array within call Photos. For example:

[
    {
        "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",
            }
        ]
    }
]

If I upload a new photo I need to update the array. I know the vehicleId, photoId and photoUrl. Pushing onto the array I get an error:

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

Where am I going wrong?

wangdev87
  • 8,611
  • 3
  • 8
  • 31
RGriffiths
  • 5,722
  • 18
  • 72
  • 120
  • 1
    What is `vehicleId`? Is it the index of the element or the `id` in the object? To access the second object's photos you can use `this.vehicles[1].photos` but not `this.vehicles[264].photos`. – Zsolt Meszaros Dec 15 '20 at 10:37
  • Yes - shown as id in the root array. id within the photos array is the photoId – RGriffiths Dec 15 '20 at 10:39
  • Still unclear to me. Assuming that outer array is `this.vehicles`, it has two elements: `this.vehicles[0]` and `this.vehicles[1]`. So again, if `vehicleId` is 251 or 264, this will not work (and please always post the error message) –  Dec 15 '20 at 10:43
  • 2
    Duplicate: [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) –  Dec 15 '20 at 10:44

1 Answers1

2

this.vehicles is the array and you should find index where the vehicleID is.

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.
}
wangdev87
  • 8,611
  • 3
  • 8
  • 31