Use the delete operator to Remove a key (or property) from an object in JavaScript. The delete
operator allows you to remove a property from an object.
If JavaScript successfully removes the key from the object, then the delete
expression will return true
.
Remove key from object JavaScript examples
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script >
let animals = {
'Cow': 'Moo',
'Cat': 'Meow',
'Dog': 'Bark'
};
delete animals.Cow;
delete animals['Dog'];
console.log(animals);
</script>
</body>
</html>
Output:
How to find and remove the object key-value pair in JavaScript?
Answer: To find and remove an object key-value pair in JavaScript, you can use a combination of the delete
operator and the Object.keys()
method or a for...in
loop. Here are examples of both methods:
Using Object.keys()
method:
const myObj = {
key1: 'value1',
key2: 'value2',
key3: 'value3'
};
// Find and remove key2 from myObj
if (myObj.hasOwnProperty('key2')) {
delete myObj.key2;
}
console.log(myObj);
Using for...in
loop:
const myObj = {
key1: 'value1',
key2: 'value2',
key3: 'value3'
};
// Find and remove key2 from myObj
for (let key in myObj) {
if (key === 'key2') {
delete myObj[key];
}
}
console.log(myObj); // Output: { key1: 'value1', key3: 'value3' }
Output: { key1: ‘value1’, key3: ‘value3’ }
Do comment if you have any doubts or suggestions on this JS object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version