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)
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)
Share Improve this question asked May 16, 2011 at 8:48 LeemLeem 18.3k39 gold badges112 silver badges164 bronze badges 06 Answers
Reset to default 6so 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={};
What's wrong with
myobj = {};
or
myobj = new Object();
?
Set myobj to empty object,
myobj = {};
The quickest/easiest way to do this is:
myobj = {};
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"}
setEmptyObject(a);
console.log(a); //{"name":"Tom", "site":"http://mymusi"}
EX 2 using emptyObject() alternative (function defined above):
var a = {"name":"Tom", "site":"http://mymusi"}
emptyObject(a);
console.log(a); //{}
One line:
Object.keys(obj).forEach( k => delete obj[k])