0

Basically what I want to do is, to use single object everytime after make it empty when my purpose is served.
For array in javascript, I used to write arr.length=0 to make any array empty, instead of pointing it to different memory location. is there any way through which I can empty an object in javascript ?
Scenario is:

var obj = {};
obj["name"]="Aman";
obj["country"]="India";
console.log(obj); // output is { name: 'Aman', country: 'India' }

Can I reused this obj object after removing its content ? if so how ?

8
  • 7
    JSON is a data format. You are talking about "an object", there's nothing JSON about it. Commented Oct 17, 2013 at 7:07
  • @JoeSimmons — That wouldn't empty any other references to the same object. Commented Oct 17, 2013 at 7:08
  • @Quentin Yes I agree that JSON is a data format, but what my purpose is to make it empty. Commented Oct 17, 2013 at 7:09
  • You'll have to use a for..in loop to erase the properties. You should also use hasOwnProperty to make sure you only delete its own properties. Commented Oct 17, 2013 at 7:10
  • 1
    Remove the word JSON from your question and title. It has nothing to do with JavaScript objects. Commented Oct 17, 2013 at 7:11

3 Answers 3

4

The only way I can think of would be to loop over the object and delete each property in turn.

var obj = {};
obj["name"]="Aman";
obj["country"]="India";

for (var prop in obj) {
    // Possibly with a hasOwnProperty test, depending on how empty you want it to be
    delete obj[prop];
}

console.log(obj);

Obviously, if you aren't dealing with multiple references to the object, you can just overwrite it with a new one.

var obj = {};
obj["name"]="Aman";
obj["country"]="India";

obj = {};

console.log(obj);
Sign up to request clarification or add additional context in comments.

4 Comments

Be sure to use hasOwnProperty -- don't want to be deleting any custom prototype methods.
appreciated... Thanks :)
For how to do the first option in TypeScript, see stackoverflow.com/q/67323880/8772169
Please note that the two ways differ in one important point if you use them on a parameter within a function. Way 1 will modify the object also outside the function, way 2 will not do that.
2
for (var member in myObject) {
    if ( myObject.hasOwnProperty(member) ) {
        delete myObject[member];
    }
}

1 Comment

Be sure to use hasOwnProperty -- don't want to be deleting any custom prototype methods.
0

use ECMAScript 6 Map:

var obj = new Map();
obj.set("name", "Aman");
obj.set("country", "India");
obj.clear();

2 Comments

I am not sure... but is it supported in all browsers ?
@Aman, not yet, but i hope somebody will investigate why Map was added to the spec

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.