EN
JavaScript - how to clear object
3
points
In this article, we would like to show you how to clear an object in JavaScript.
Below examples show two solutions on how to do that:
- Assigning the object to a new empty object (
{}
), - Using
for
loop todelete
the object's properties.
Solution 1
In this solution, we create a new memory location with an empty object ({}
) and we point existing object to that location.
Runnable solution:
// ONLINE-RUNNER:browser;
var user = {
id: 1,
name: 'John',
age: 43
};
user = {};
console.log(JSON.stringify(user, null, 4)); // {}
Note:
If we want to use this approach, the object cannot beconst
.
Solution 2
In this solution, we use for loop to iterate over object properties and delete them.
Runnable solution:
// ONLINE-RUNNER:browser;
const user = {
id: 1,
name: 'John',
age: 43
};
for (var prop in user) {
if (user.hasOwnProperty(prop)) {
delete user[prop];
}
}
console.log(JSON.stringify(user, null, 4)); // {}
Note:
This approach is slow when we're dealing with large objects.