delete multiple properties from object javascript
Deleting Multiple Properties from Object in JavaScript
If you have an object with many properties and you need to delete some of them, you can use the delete
operator in JavaScript. Here's how:
Using the delete operator
let myObj = {
name: "John",
age: 30,
city: "New York",
country: "USA"
};
delete myObj.age;
delete myObj.country;
console.log(myObj); // {name: "John", city: "New York"}
In the above example, we have an object with properties name
, age
, city
, and country
. We use the delete
operator to remove the age
and country
properties from the object. After deletion, the object now has only two properties: name
and city
.
Using Object.keys()
If you want to delete multiple properties from an object at once, you can use the Object.keys()
method to get an array of all the property names, and then loop through that array to delete the desired properties:
let myObj = {
name: "John",
age: 30,
city: "New York",
country: "USA"
};
let propsToDelete = ["age", "country"];
for(let prop of propsToDelete) {
delete myObj[prop];
}
console.log(myObj); // {name: "John", city: "New York"}
In the above example, we have an object with properties name
, age
, city
, and country
. We create an array called propsToDelete
containing the names of the properties we want to delete. We then loop through this array using a for...of
loop, and delete each property from the object using the delete
operator. After deletion, the object now has only two properties: name
and city
.