How do I remove a key from a JavaScript object?

Links for php scripts

Moderators: gesf, Michalio

Post Reply
hannabone3445

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

Code: Select all

var thisIsObject= {
   'Cow' : 'Moo',
   'Cat' : 'Meow',
   'Dog' : 'Bark'
};
I wanted to do a function that removes by key:

Code: Select all

removeFromObjectByKey('Cow');
Strider64

hannabone3445 wrote: Tue Sep 21, 2021 2:39 pm Let's say we have an object with this format:

Code: Select all

var thisIsObject= {
   'Cow' : 'Moo',
   'Cat' : 'Meow',
   'Dog' : 'Bark'
};
I wanted to do a function that removes by key:

Code: Select all

removeFromObjectByKey('Cow');
just use delete thisisObject.cow and use a switch statement or if statements (I would use a switch statement)
simonbrahan

Your function will also need to accept the object.

Code: Select all

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.
Post Reply