0

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

2
  • 2
    myArray.value is undefined. Did you mean myArray.findIndex(...)? Commented Oct 4, 2022 at 17:38
  • findIndex() seems to just return the index of specific element, you can use this index as parameter in myArray.splice(index,1) Commented Oct 4, 2022 at 17:46

3 Answers 3

3

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.