Javascript 在一个数组中推送到一个数组上
我有一个阵列车辆,在呼叫照片中有一个阵列。例如:Javascript 在一个数组中推送到一个数组上,javascript,arrays,vue.js,Javascript,Arrays,Vue.js,我有一个阵列车辆,在呼叫照片中有一个阵列。例如: [ { "id": 251, "make": "Toyota", "model": "Land Cruiser ", "photos": [ { "id": 7,
[
{
"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",
}
]
}
]
如果我上传一张新照片,我需要更新阵列。我知道车辆ID、照片ID和照片URL。推到阵列上时,我得到一个错误:
this.vehicles[vehicleId].photos.push({id: photoId, photoUrl: photoUrl})
我哪里出错了?
这个。vehicles
是数组,您应该找到vehicleID所在的索引
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.
}
什么是
车辆ID
?它是元素的索引还是对象中的id
?要访问第二个对象的照片,可以使用this.vehicles[1].photos
,但不能使用this.vehicles[264].photos
.Yes-在根数组中显示为id。照片数组中的id是我不清楚的照片id。假设外部数组是this.vehicles
,它有两个元素:this.vehicles[0]
和this.vehicles[1]
。同样,如果vehicleId
为251或264,这将不起作用(请始终发布错误消息)重复:使用find()
而不是findIndex()
,不是更容易吗?请不要发布明显重复的答案。