Languages
[Edit]
EN

JavaScript - how to clear object

6 points
Created by:
Olivier-Myers
514

In this article, we would like to show you how to clear an object in JavaScript.

The below examples show solutions that:

  1. assign new empty object ({}),
  2. 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));  // {}

 

Alternative titles

  1. JavaScript - how to empty object
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join