首页 > 解决方案 > 按 id 删除数组对象

问题描述

我正在尝试通过 id 删除离子存储中的数组对象。但它没有按预期工作..我该怎么办。这是我的代码

页面.ts

 removeItem(id){
    this.storage.get('storedAdd').then((val) => {
      console.log(Object.keys(val))
      Object.keys(val).splice(id, 1)
      console.log(val)
     for(let element of Object.keys(val)){
        console.log(val[element])
        val[element].id.toString().splice(id,1)
         this.storage.set('storeAdd', val)
          console.log(val)
     }
}

我使用拼接但收到此错误

ERROR Error: Uncaught (in promise): TypeError: val[element].id.toString(...).splice is not a function
TypeError: val[element].id.toString(...).splice is not a function

编辑 在此处输入图像描述

标签: angulartypescriptionic-frameworkarray-splice

解决方案


我认为您不能在那里使用 toString ,因为splice() 方法通过删除或替换现有元素和/或在适当位置添加新元素来更改数组的内容。 删除键的示例为 0:我使用了 delete

let myObject = {
  0: {
        "id" : 1,
        "text": "text1"
    },
 1: {
        "id" : 2,
        "text": "text2"
    }
};

delete myObject[0];
console.log(myObject);

推荐阅读