Reputation: 18328
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
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
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