Wednesday, November 28, 2018

Remove a Single Object from a Javascript Object




How do I remove one item based on both the courseID and endDate from the following javascript object?



    window.MyCheckedCourses = [
{ courseID: '123', endDate: '6/7/2010' },
{ courseID: '123', endDate: '3/9/2003' },
{ courseID: '456', endDate: '3/9/2003' }
];


Answer



Iteration is a must. You have to use .splice() to remove corresponding item and break the for loop.



var i, id = '123', date = '6/7/2010';
for(var i = 0, il = MyCheckedCourses.length;i if(MyCheckedCourses[i].courseID == id && MyCheckedCourses[i].endDate == date) {
MyCheckedCourses.splice(i, 1);
break;
}

}


You can make a function and use it with parameters like this;



function remove(id, date) {
for(var i = 0, il = MyCheckedCourses.length;i if(MyCheckedCourses[i].courseID == id && MyCheckedCourses[i].endDate == date) {
MyCheckedCourses.splice(i, 1);
break;

}
}
}
// Example usage:
remove('123', '6/7/2010');


Edit after Ian's comment:



I assume that your collection have unique items. If not you have to iterate through all items and you have to do it backwards because if you remove an element from array it's index will change and iteration will not work correctly. So this function is a much more safer version;




function remove(id, date) {
for(var i = MyCheckedCourses.length - 1;i >= 0;i--) {
if(MyCheckedCourses[i].courseID == id && MyCheckedCourses[i].endDate == date) {
MyCheckedCourses.splice(i, 1);
}
}
}
// Example usage:
remove('123', '6/7/2010');


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...