首页 > 解决方案 > 从数组集合中删除子对象

问题描述

我将从 API 返回的数据分配给一个名为的变量today,我正在尝试对其执行删除功能,但我总是收到此错误Cannot read property 'id' of undefined

数据

[
    {
        "id":324,
        "firstName":"Chris",
        "lastName":"Jake",
        "orders":[
            {
                "id":162,
                "meals":[
                    {
                        "id":27,
                        "name":"French Fries",
                        "description":"test",
                    },
                    {
                        "id":28,
                        "name":"Plain Rice, Beans and Fish",
                        "description":"test",
                    }
                ],
                "serveDate":"2019-07-16 00:00:00"
            }
        ]
    }
]

功能

delete() {
    for (let r = 0; r < this.today.length; r++) {
        if (this.today[r].orders[r].id === this.orderId) {
            this.today.splice(r, 1);
        }
    }
}

标签: javascriptangulartypescript

解决方案


您的“serverDate”也是数组的一个元素,它没有 id,因此您会收到此错误。如果未定义,order[r].id 将返回 false。

  delete() {
      for (let r = 0; r < this.today.length; r++) {
            if (this.today[r].orders[r].id && 
                this.today[r].orders[r].id ===   this.orderId) {
                this.today.splice(r, 1);
            }
      }
  }

推荐阅读