How can I delete/unset the properties of a JavaScript object?

JavascriptJquery

Javascript Problem Overview


> Possible Duplicates:
> How can I unset a JavaScript variable?
> How do I remove a property from a JavaScript object?

I'm looking for a way to remove/unset the properties of a JavaScript object, so they'll no longer come up if I loop through the object doing for (var i in myObject). How can this be done?

Javascript Solutions


Solution 1 - Javascript

Simply use delete, but be aware that you should read fully what the effects are of using this:

 delete object.index; //true
 object.index; //undefined

But if I was to use like so:

var x = 1; //1
delete x; //false
x; //1

But if you do wish to delete variables in the global namespace, you can use its global object such as window, or using this in the outermost scope, i.e.,

var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true

Understanding delete

Another fact is that using delete on an array will not remove the index, but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity. When it comes to arrays you should use splice which is a prototype of the array object.

Example Array:

var myCars = new Array();
myCars[0] = "Saab";
myCars[1] = "Volvo";
myCars[2] = "BMW";

If I was to do:

delete myCars[1];

the resulting array would be:

["Saab", undefined, "BMW"]

But using splice like

myCars.splice(1,1);

would result in:

["Saab", "BMW"]

Solution 2 - Javascript

To blank it:

myObject["myVar"]=null;

To remove it:

delete myObject["myVar"]

as you can see in duplicate answers

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAliView Question on Stackoverflow
Solution 1 - JavascriptRobertPittView Answer on Stackoverflow
Solution 2 - JavascriptmplungjanView Answer on Stackoverflow