EN
JavaScript - how to clear object
6
points
In this article, we would like to show you how to clear an object in JavaScript.
The below examples show solutions that:
- assign new empty object (
{}
), - delete 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;
let user = {
id: 1,
name: 'John',
age: 43
};
user = {}; // empty object operation
console.log(JSON.stringify(user, null, 4)); // {}
Notes:
- in that approach, the object cannot be
const
,- that approach changes variable reference.
Solution 2
In this section, we use for
loop to iterate over object properties and delete them.
Note: that approaches are slow when we empty large objects.
2.1. for..in loop solution
Runnable solution:
// ONLINE-RUNNER:browser;
const emptyObject = (object) => {
for (const name in object) {
if (object.hasOwnProperty(name)) {
delete object[name];
}
}
};
// Usage example:
const user = {
id: 1,
name: 'John',
age: 43
};
emptyObject(user); // empty object operation
console.log(JSON.stringify(user, null, 4)); // {}
2.2. Object.keys()
method solution
Runnable solution:
// ONLINE-RUNNER:browser;
const emptyObject = (object) => {
const keys = Object.keys(object);
for (const key of keys) {
delete object[key];
}
};
// Usage example:
const user = {
id: 1,
name: 'John',
age: 43
};
emptyObject(user); // empty object operation
console.log(JSON.stringify(user, null, 4)); // {}