Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I remove a property from a JavaScript object?

Remove Property from an ObjectThe delete operator deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions.

How do I remove all properties of an object?

Use a for..in loop to clear an object and delete all its properties. The loop will iterate over all the enumerable properties in the object. On each iteration, use the delete operator to delete the current property. Copied!

How do you remove duplicate objects?

To remove the duplicates from an array of objects:Create an empty array that will store the unique object IDs. Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.

How do you remove the Falsy value of an object?

To remove the falsy values from an object, pass the object to the Object. keys() method to get an array of the object's keys. Use the forEach() method to iterate over the array and delete each falsy value from the object.


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"]

To blank it:

myObject["myVar"]=null;

To remove it:

delete myObject["myVar"]

as you can see in duplicate answers