Remove Property from Javascript Object
Methods used to delete an attribute of an object or to delete an item from an array becomes confusing when you are not clear how they work also using incorrect way of doing things may introduce bugs to a system without knowing.
Lets look at deleting an item from an Array
- Using “delete“
var friends = [ "a" , "b", "c" ]; var deleteIndex = 1; delete friends[deleteIndex]; console.log(friends); console.log(friends.length);
looks ok right ? Nooo, Look close and you will notice that something is wrong. even though you don’t see “a” anymore in the array the length is still 3 !!!!
- Using “splice“
var friends = [ "a" , "b", "c" ]; var deleteIndex = 1; friends.splice(deleteIndex,1); console.log(friends); console.log(friends.length);
Now this looks perfect. we don’t see “a” anymore and index is also 2
So take away from above demo is that you should not be using delete for array objects instead you should use splice
Lets look at deleting an attribute from an Object
var friend = { name : "john", age : 10 } delete friend.name; console.log(friend);
or
var friend = { name : "john", age : 10 } delete friend['name']; console.log(friend);
Above both code has successfully deleted the “name” attribute so both ways safe to use.