Skip to content
the poor coder

delete multiple properties from object javascript

Poor Man
Published
Reading time
1 min read
On this page

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#

Text
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:

Text
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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC