How do I remove a key from a JavaScript object?

A

Anonymous

Guest
Let's say we have an object with this format:
Code:
var thisIsObject= {
   'Cow' : 'Moo',
   'Cat' : 'Meow',
   'Dog' : 'Bark'
};

I wanted to do a function that removes by key:
Code:
removeFromObjectByKey('Cow');
 
hannabone3445 said:
Let's say we have an object with this format:
Code:
var thisIsObject= {
   'Cow' : 'Moo',
   'Cat' : 'Meow',
   'Dog' : 'Bark'
};

I wanted to do a function that removes by key:
Code:
removeFromObjectByKey('Cow');

just use delete thisisObject.cow and use a switch statement or if statements (I would use a switch statement)
 
Your function will also need to accept the object.

Code:
function removeFromObjectByKey(obj, propName) {
    delete obj[propName];
}

var foo = { a: 'able', b: 'baker' };

removeFromObject(foo, 'b');

The above will work. You're probably just as well using the "delete" call in a single line though.
 
Back
Top