简体   繁体   中英

Deleting single object from array of objects

I have the following collection of objects, which I converted to an array of objects using 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 }) );

I would like to delete an object from the array based on the 'id'.

Here's what I've done so far but it isn't working :

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

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

Firstly myArray.value.findIndex is wrong; it should be myArray.findIndex . You can use splice function to remove the index as per the snippet below

 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)

Do you need to have a function for that? If it's not the case I can suggest you to use the filter method instead. Try this one:

yourArrayOfObjects.filter(object => {
    object.id !== id
})

This method iterates through the keys in your object and deletes matching IDs. If IDs are unique, you can add a return statement after delete.

function deleteObject(id) {
    for (let key in demoObject) {
        if (demoObject[key].ADMISSION_ID === id) {
            delete demoObject[key];
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM