Search code examples
javascriptarraysjavascript-objects

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


Solution

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