最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - newbie: How to clean up an object in javascript? - Stack Overflow

programmeradmin5浏览0评论

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 0
Add a ment  | 

6 Answers 6

Reset to default 6

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={};

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])
发布评论

评论列表(0)

  1. 暂无评论