开发者问题收集

从对象数组中删除单个对象

2022-10-04
97

我有以下对象集合,我使用 Object.values 将其转换为对象数组。

let demoObject = {
  "abc": {
    "ADMISSION_ID": 1632881,
    "ADDITIONAL_DATA": null,
    "CREATED_BY": "7348500"
  },
  "def": {
    "ADMISSION_ID": 1632790,
    "ADDITIONAL_DATA": null,
    "CREATED_BY": "7348500"
  },
  "ijk": {
    "ADMISSION_ID": 1619783,
    "ADDITIONAL_DATA": null,
    "CREATED_BY": "7346831"
  }
}
const myArray = [];
Object.values(demoObject).forEach(val =>
  myArray.push({
    id: val.ADMISSION_ID,
    header: val.HOSPITAL_GROUP_ID,
    date: val.CREATED_DATE
  })
);

我想根据“id”从数组中删除一个对象。

这是我到目前为止所做的,但它没有 工作

const deleteObject = (id) => {
   myArray.value.findIndex((array) => array.id == id);
}
deleteObject(1632881)

Uncaught TypeError: Cannot read properties of undefined (reading 'findIndex')

3个回答

首先, myArray.value.findIndex 是错误的;它应该是 myArray.findIndex 。 您可以按照以下代码片段使用 splice 函数删除索引

let demoObject =  { "abc":
{
    "ADMISSION_ID" : 1632881,
    "ADDITIONAL_DATA" : null,
    "CREATED_BY" : "7348500"
},
"def": {
    "ADMISSION_ID" : 1632790,
    "ADDITIONAL_DATA" : null,
    "CREATED_BY" : "7348500"
},
"ijk":{
    "ADMISSION_ID" : 1619783,
    "ADDITIONAL_DATA" : null,
    "CREATED_BY" : "7346831"
}}
const myArray = [];
Object.values(demoObject).forEach(val => 
myArray.push({id: val.ADMISSION_ID, header: val.HOSPITAL_GROUP_ID, date: val.CREATED_DATE})                                 
);
const deleteObject = (id) => {
   const index = myArray.findIndex(array => array.id === id)
   myArray.splice(index, 1)
   console.log(myArray)
}
deleteObject(1632881)
otejiri
2022-10-04

您需要为此创建一个函数吗?如果不需要,我建议您改用过滤方法。试试这个:

yourArrayOfObjects.filter(object => {
    object.id !== id
})
Marat
2022-10-04

此方法遍历对象中的键并删除匹配的 ID。如果 ID 是唯一的,您可以在删除后添加返回语句。

function deleteObject(id) {
    for (let key in demoObject) {
        if (demoObject[key].ADMISSION_ID === id) {
            delete demoObject[key];
        }
    }
}
Ethan R
2022-10-04