【问题标题】:Pushing onto an array within an array [duplicate]推入数组中的数组[重复]
【发布时间】:2020-12-15 10:36:09
【问题描述】:

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

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

如果我上传新照片,我需要更新数组。我知道vehicleId、photoId 和photoUrl。推入数组我得到一个错误:

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

我哪里错了?

【问题讨论】:

  • 什么是vehicleId?是元素的索引还是对象中的id?要访问第二个对象的照片,您可以使用this.vehicles[1].photos,但不能使用this.vehicles[264].photos
  • 是 - 在根数组中显示为 id。照片数组中的 id 是 photoId
  • 我还不清楚。假设外部数组是this.vehicles,它有两个元素:this.vehicles[0]this.vehicles[1]。同样,如果vehicleId 是 251 或 264,这将不起作用(请始终发布错误消息)

标签: javascript arrays vue.js


【解决方案1】:

this.vehicles 是数组,您应该找到车辆 ID 所在的索引。

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.
}

【讨论】:

  • find()代替findIndex()不是更方便吗?
  • 请不要发布明显重复的答案。
猜你喜欢
  • 1970-01-01
  • 2020-10-22
  • 2013-01-07
  • 1970-01-01
  • 1970-01-01
  • 2021-01-14
  • 2017-03-28
  • 2018-11-21
相关资源
最近更新 更多