Home > OS >  Deleting single object from array of objects
Deleting single object from array of objects

Time:10-05

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')

CodePudding user response:

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)

CodePudding user response:

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];
        }
    }
}

CodePudding user response:

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
})
  • Related