Leem
Leem

Reputation: 18328

newbie: How to clean up an object in javascript?

If I have an object:

var myobj={name: 'Some Value',
           id: 'my id',
           address: 'my address'
           ...}

myobj has been extended dynamically, by myobj[custom_attribute]=SOME_VALUE

I would like to clean up this object to have empty attribute, that's myobj={}, how to do it? (I do not want to use for loop to clean up the attribute one by one)

Upvotes: 1

Views: 8524

Answers (6)

basil
basil

Reputation: 3612

One line:

Object.keys(obj).forEach( k => delete obj[k])

Upvotes: 0

Tom G
Tom G

Reputation: 3660

The other answers are fine if you are not editing an object by reference. However, if you pass an object into a function and you want the original object to be affected as well you can use this function:

function emptyObject(objRef) {
    for(var key in objRef) {
        if(objRef.hasOwnProperty(key)) {
            delete objRef[key];
        }
    }
}

This maintains the original object reference and is good for plugin authoring where you manage an object that is provided as parameter. Two quick examples will show how this differs from simply setting the object equal to {}

EX 1:

function setEmptyObject(obj) {
    obj = {};
}
var a = {"name":"Tom", "site":"http://mymusi.cc"}
setEmptyObject(a);
console.log(a); //{"name":"Tom", "site":"http://mymusi.cc"}

EX 2 using emptyObject() alternative (function defined above):

var a = {"name":"Tom", "site":"http://mymusi.cc"}
emptyObject(a);
console.log(a); //{}

Upvotes: 1

Nanne
Nanne

Reputation: 64419

so you want to assign myobj={}, to make it empty? Pardon me if I read your question wrong, but it seems to me you want to do

myobj={};

Upvotes: 6

Raoul
Raoul

Reputation: 3899

The quickest/easiest way to do this is:

myobj = {};

Upvotes: 2

Amitabh
Amitabh

Reputation: 61287

Set myobj to empty object,

myobj = {};

Upvotes: 4

SirViver
SirViver

Reputation: 2441

What's wrong with

myobj = {};

or

myobj = new Object();

?

Upvotes: 4

Related Questions