In this article we will learn how to clear an object in JavaScript.
It is very common to clear an object in JavaScript in JavaScript.
Problem
Now we have a problem which is that we want to clear an object.
Now let's imagine that we have an object like this:
const myObject = {
name: "John",
age: 30,
country: "USA",
};
And we want to clear this object
How to solve this problem?
Fortunately, there is more than one solution to this problem, and there are many functions that will help us solve this problem like delete
method, solutions such as:
- Using
for .. in
method. - Using reassigning
obj = {}
- Using
Object.keys
Clear an object using for .. in
and delete
We can use for .. in
to iterate over an object and then delete values using delete
operator.
Let's see an example
// Object
const myObject = {
name: "John",
age: 30,
country: "USA"
}
// Delete values
for(let key in myObject) {
delete myObject[key];
}
// Result:
console.log(myObject);
Output
{}
The for...in statement iterates over all enumerable string properties of an object (ignoring properties keyed by symbols), including inherited enumerable properties. MDN
Clear an object using reassigning
We can use reassigning to clear our object.
// Object
const myObject = {
name: "John",
age: 30,
country: "USA"
}
// reassigning
myObject = {};
// Result:
console.log(myObject);
Output
{}
Clear an object using Object.keys
We can use Object.keys
to get an array of the object's keys, And then use the Array.forEach()
method to iterate over the array, And delete values using delete
operator.
Let's see an example
// Object
const myObject = {
name: "John",
age: 30,
country: "USA"
}
// Delete values
Object.keys(myObject).forEach(key => {
delete myObject[key];
})
// Result:
console.log(myObject);
Thank you for reading
Thank you for reading my blog. 🚀