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.
In this solution, we create a new memory location with an empty object ({}
) and we point existing object to that location.
Runnable solution:
xxxxxxxxxx
1
let user = {
2
id: 1,
3
name: 'John',
4
age: 43
5
};
6
7
user = {}; // empty object operation
8
9
console.log(JSON.stringify(user, null, 4)); // {}
Notes:
- in that approach, the object cannot be
const
,- that approach changes variable reference.
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.
Runnable solution:
xxxxxxxxxx
1
const emptyObject = (object) => {
2
for (const name in object) {
3
if (object.hasOwnProperty(name)) {
4
delete object[name];
5
}
6
}
7
};
8
9
10
// Usage example:
11
12
const user = {
13
id: 1,
14
name: 'John',
15
age: 43
16
};
17
18
emptyObject(user); // empty object operation
19
20
console.log(JSON.stringify(user, null, 4)); // {}
Runnable solution:
xxxxxxxxxx
1
const emptyObject = (object) => {
2
const keys = Object.keys(object);
3
for (const key of keys) {
4
delete object[key];
5
}
6
};
7
8
9
// Usage example:
10
11
const user = {
12
id: 1,
13
name: 'John',
14
age: 43
15
};
16
17
emptyObject(user); // empty object operation
18
19
console.log(JSON.stringify(user, null, 4)); // {}