kittu
kittu

Reputation: 7018

Error while deleting object in javascript

I get undefined error while deleting object from list of objects.

Html:

<div>
<p each="{holidayListSecondPart, i in this.holidayListSecondPart}">
    <span id="{holidayListSecondPart.description}">{holidayListSecondPart.description}</span>

    <span id="delete{i+1}" onclick="{remove}">delete</span>

    <span id="editHoliday{i+1}" onclick="{editHoliday}">edit</span>
</p>
</div>

js code:

remove(e){
    e.target.parentNode.remove();
    console.log('DataMixin.data before delete ', DataMixin.data.holidayList);
    self.deletingId = e.target.parentNode.firstElementChild.id;
    for(var i = 0; i<Object.keys(DataMixin.data.holidayList).length; i++){
        if(self.deletingId == DataMixin.data.holidayList[i+1].reason){
            console.log("delete ID matched: ", i+1);
            console.log('ID to be deleted is: ' , DataMixin.data.holidayList[i+1]);
            delete DataMixin.data.holidayList[i+1];
        }
    }
    console.log('DataMixin.data after delete ', DataMixin.data.holidayList);
}

List of object looks like this:

List of objects

After deleting the first object, I try to delete third object its throwing error:

Uncaught TypeError: Cannot read property 'reason' of undefined

I am sure some thing wrong with looping logic but I am not able to get my head around it. Where did I go wrong?

Update:

I am trying to delete an element from DOM and its property from Javascript object on click like below:

enter image description here

Upvotes: 0

Views: 347

Answers (1)

Dauren
Dauren

Reputation: 36

If you deleting objects from your DataMixin.data.holidayList, you cannot run through an object from 0 index to Object.keys(DataMixin.data.holidayList).length again. Because you deleted one of its fields (lets say object with index 3), when function will do this part:

//i == 3
if(self.deletingId == DataMixin.data.holidayList[i+1].reason){
        //code
}

You will get Cannot read property 'reason' of undefined error, cause you deleted this field. You should use this:

for (var property in DataMixin.data.holidayList){
  if (DataMixin.data.holidayList.hasOwnProperty(property)){
    //put your code for each property here
  }
}

Or you can use this method:

Object.keys(obj).forEach(function(key,index) {
// key: the name of the object key
// index: the ordinal position of the key within the object 
});

Upvotes: 1

Related Questions