How to delete object property?

与世无争的帅哥 提交于 2020-02-08 09:47:26

问题


According to the docs the delete operator should be able to delete properties from objects. I am trying to delete properties of an object that are "falsey".

For example, I assumed the following would remove all of the falsey properties from testObj but it does not:

    var test = {
        Normal: "some string",  // Not falsey, so should not be deleted
        False: false,
        Zero: 0,
        EmptyString: "",
        Null : null,
        Undef: undefined,
        NAN: NaN                // Is NaN considered to be falsey?
    };

    function isFalsey(param) {
        if (param == false ||
            param == 0     ||
            param == ""    ||
            param == null  ||
            param == NaN   ||
            param == undefined) {
            return true;
        }
        else {
            return false;
        }
    }

// Attempt to delete all falsey properties
for (var prop in test) {
    if (isFalsey(test[prop])) {
        delete test.prop;
    }
}

console.log(test);

// Console output:
{ Normal: 'some string',
  False: false,
  Zero: 0,
  EmptyString: '',
  Null: null,
  Undef: undefined,
  NAN: NaN 
}

回答1:


Use delete test[prop] instead of delete test.prop because with the second approach you are trying to delete the property prop literally (which you doesn't have in your object). Also by default if a object has a value which is null,undefined,"",false,0,NaN using in a if expression or returns false, so you can change your isFalsey function to

 function isFalsey(param) {
     return !param;
 }

Try with this code:

var test = {
        Normal: "some string",  // Not falsey, so should not be deleted
        False: false,
        Zero: 0,
        EmptyString: "",
        Null : null,
        Undef: undefined,
        NAN: NaN                // Is NaN considered to be falsey?
    };

    function isFalsey(param) {
        return !param;
    }

// Attempt to delete all falsey properties
for (var prop in test) {
    if (isFalsey(test[prop])) {
        delete test[prop];
    }
}

console.log(test);


来源:https://stackoverflow.com/questions/28571651/how-to-delete-object-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!