You can use the delete
operator to Remove key-value from object JavaScript. When only a single key is to be removed we can directly use the delete operator specifying the key in an object.
delete(object_name.key_name); // or delete(object_name[key_name]);
Remove key-value from object JavaScript example
In simple example code to remove the key-value pair with key ‘b’, we use the delete
operator followed by the object name and the key we want to remove. After deleting the key-value pair, we print the modified object to the console using console.log()
.
<!DOCTYPE html>
<html>
<body>
<script >
let obj = {a: 1, b: 2, c: 3};
// removes the key-value pair with key 'b'
delete obj.b;
console.log(obj);
</script>
</body>
</html>
Output:
Another example
<!DOCTYPE html>
<html>
<body>
<script >
var myObj = {
Name: "John",
Age: 30,
Sex: "Male",
Work: "Coder",
YearsOfExperience: 6,
Address: "Bangalore"
};
console.log("After removal: ");
delete (myObj.Address); // Or delete(myObj[Address]);
console.log(myObj);
</script>
</body>
</html>
Output:
Remove the key-value pair from an object having values as another array of objects.
var valGroup = {
"Tier1": [
{
"DE": 0,
"CreditRange": "0",
"VintageCriteria": [],
"DBR": 0,
"NetsalesCriteria": [],
"ABBmultiplier": 0,
"BTO": 0,
"MUE": [],
"TurnoverCriteria": 0,
"DSCR": 0,
"category": "Tier1"
},
{
"DE": 0,
"CreditRange": "0",
"VintageCriteria": [],
"DBR": 0.8,
"NetsalesCriteria": [],
"ABBmultiplier": 0,
"BTO": 0,
"MUE": [],
"TurnoverCriteria": 0,
"DSCR": 0,
"category": "Tier1"
}
],
"Tier2": [
{
"DE": 0,
"CreditRange": "0",
"VintageCriteria": [],
"DBR": 0,
"NetsalesCriteria": [],
"ABBmultiplier": 0,
"BTO": 0,
"MUE": [],
"TurnoverCriteria": 0,
"DSCR": 0,
"category": "Tier2"
},
{
"DE": 0,
"CreditRange": "",
"VintageCriteria": [],
"DBR": 0,
"NetsalesCriteria": [],
"ABBmultiplier": 0,
"BTO": 0,
"MUE": [],
"TurnoverCriteria": 0,
"DSCR": 0,
"category": "Tier2"
}
]
}
const result = Object.fromEntries([
...Object.keys(valGroup)
.map(key => [key, valGroup[key].map(({category, ...rest}) => rest)])
])
console.log(result);
Output:
{
"Tier1": [
{
"DE": 0,
"CreditRange": "0",
"VintageCriteria": [],
"DBR": 0,
"NetsalesCriteria": [],
"ABBmultiplier": 0,
"BTO": 0,
"MUE": [],
"TurnoverCriteria": 0,
"DSCR": 0
},
{
"DE": 0,
"CreditRange": "0",
"VintageCriteria": [],
"DBR": 0.8,
"NetsalesCriteria": [],
"ABBmultiplier": 0,
"BTO": 0,
"MUE": [],
"TurnoverCriteria": 0,
"DSCR": 0
}
],
"Tier2": [
{
"DE": 0,
"CreditRange": "0",
"VintageCriteria": [],
"DBR": 0,
"NetsalesCriteria": [],
"ABBmultiplier": 0,
"BTO": 0,
"MUE": [],
"TurnoverCriteria": 0,
"DSCR": 0
},
{
"DE": 0,
"CreditRange": "",
"VintageCriteria": [],
"DBR": 0,
"NetsalesCriteria": [],
"ABBmultiplier": 0,
"BTO": 0,
"MUE": [],
"TurnoverCriteria": 0,
"DSCR": 0
}
]
}
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