Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove a key from a JavaScript object? [duplicate]

Tags:

javascript

Let's say we have an object with this format:

var thisIsObject= {    'Cow' : 'Moo',    'Cat' : 'Meow',    'Dog' : 'Bark' }; 

I wanted to do a function that removes by key:

removeFromObjectByKey('Cow'); 
like image 656
Martin Ongtangco Avatar asked Aug 11 '10 04:08

Martin Ongtangco


People also ask

How do I delete key in on object JavaScript?

Use delete to Remove Object Keys The special JavaScript keyword delete is used to remove object keys (also called object properties). While you might think setting an object key equal to undefined would delete it, since undefined is the value that object keys that have not yet been set have, the key would still exist.

How do I remove a specific key value from an object?

Using delete operator. When only a single key is to be removed we can directly use the delete operator specifying the key in an object. Syntax: delete(object_name.

Can JavaScript object have duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

How do I remove a key from an array of objects?

To remove a property from all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use the delete operator to delete the specific property.


1 Answers

The delete operator allows you to remove a property from an object.

The following examples all do the same thing.

// Example 1 var key = "Cow"; delete thisIsObject[key];   // Example 2 delete thisIsObject["Cow"];  // Example 3 delete thisIsObject.Cow; 

If you're interested, read Understanding Delete for an in-depth explanation.

like image 50
jessegavin Avatar answered Oct 25 '22 18:10

jessegavin