HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How do I remove a key from a JavaScript object?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
keyobjecthowfromremovejavascript

Problem

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');

Solution

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;




let animals = {
'Cow': 'Moo',
'Cat': 'Meow',
'Dog': 'Bark'
};

delete animals.Cow;
delete animals['Dog'];

console.log(animals);




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

Code Snippets

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

// Example 2
delete thisIsObject["Cow"];

// Example 3
delete thisIsObject.Cow;

Context

Stack Overflow Q#3455405, score: 3221

Revisions (0)

No revisions yet.