How do I remove a key from a JavaScript object?

Links for php scripts

Moderators: egami, macek, gesf

Post Reply
User avatar
hannabone3445
New php-forum User
New php-forum User
Posts: 3
Joined: Tue Sep 21, 2021 2:26 pm
Contact:

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');
User avatar
Strider64
php-forum GURU
php-forum GURU
Posts: 429
Joined: Sat Mar 23, 2013 8:24 am
Location: Livonia, MI
Contact:

Wed Sep 22, 2021 3:19 am

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)
Life is a fig newton of your imagination! https://www.phototechguru.com/
simonbrahan
php-forum Super User
php-forum Super User
Posts: 153
Joined: Mon Jun 08, 2020 2:00 am
Contact:

Thu Sep 23, 2021 12:13 am

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