考虑到一个对象:

let myObject = {
  "ircEvent": "PRIVMSG",
  "method": "newURI",
  "regex": "^http://.*"
};

如何删除财产 regex 以完成下一个 myObject?

let myObject = {
  "ircEvent": "PRIVMSG",
  "method": "newURI"
};

当前回答

我们可以使用

使用删除 object.property 使用删除 object[‘property’] 使用休息,删除多个属性

让 myObject = { “ircEvent”: “PRIVMSG”, “method”: “newURI”, “regex”: “^http://.*”, “regex1”: “^http://.*”, “regex2”: “^http://.*”, “regex3”: “^http://.*”, “regex4”: “^http://.*” }; 删除 myObject.regex; // 使用删除 object.property // 或删除 myObject(‘regex1’); // 使用删除 object(‘property’) const { regex2, regex3, regex4,...newMyObject } = myObject; console.log(n)

其他回答

如果您想删除对物体深沉的财产,那么您可以使用下列重复功能,路径到财产作为第二个论点:

var deepObjectRemove = function(obj, path_to_key){
    if(path_to_key.length === 1){
        delete obj[path_to_key[0]];
        return true;
    }else{
        if(obj[path_to_key[0]])
            return deepObjectRemove(obj[path_to_key[0]], path_to_key.slice(1));
        else
            return false;
    }
};

例子:

var a = {
    level1:{
        level2:{
            level3: {
                level4: "yolo"
            }
        }
    }
};

deepObjectRemove(a, ["level1", "level2", "level3"]);
console.log(a);

//Prints {level1: {level2: {}}}

使用对象破坏,一个ECMAScript 6功能,它是如此简单:

const { a, ...rest } = { a: 1, b: 2, c: 3 };

或与问题样本:

const myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
const { regex, ...newObject } = myObject;
console.log(newObject);

你可以在Babel try-out编辑中看到它。


编辑:

要重新分配到相同的变量,请使用:

let myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
({ regex, ...myObject } = myObject);
console.log(myObject);

我们可以使用

使用删除 object.property 使用删除 object[‘property’] 使用休息,删除多个属性

让 myObject = { “ircEvent”: “PRIVMSG”, “method”: “newURI”, “regex”: “^http://.*”, “regex1”: “^http://.*”, “regex2”: “^http://.*”, “regex3”: “^http://.*”, “regex4”: “^http://.*” }; 删除 myObject.regex; // 使用删除 object.property // 或删除 myObject(‘regex1’); // 使用删除 object(‘property’) const { regex2, regex3, regex4,...newMyObject } = myObject; console.log(n)

Object.assign() 和 Object.keys() 和 Array.map()

const obj = { “过滤器”:[ { “过滤器类型”:”之间”, “区域”:”BasicInformationRow.A0”, “MaxValue”:”2017-10-01”, “MinValue”:”2017-09-01”, “值”:”过滤器值” } } }; let new_obj1 = Object.assign({}, obj.Filters[0]); let new_obj2 = Object.assign({}, obj.Filters[0]); /* // old version let sh

这里有很多好答案,但我只是想说,当使用删除删除在JavaScript中删除一个属性时,很常见首先检查该属性是否存在,以防止错误。

E.G

var obj = {"property":"value", "property2":"value"};

if (obj && obj.hasOwnProperty("property2")) {
  delete obj.property2;
} else {
  //error handling
}

由于JavaScript的动态性质,经常有情况,你只是不知道是否存在的财产。 检查obj是否存在之前&& 也确保你不会扔错误,因为在未定义的对象上呼叫 hasOwnProperty() 函数。

对不起,如果这并没有添加到您的具体使用案例,但我认为这是一个很好的设计,在管理对象和其属性时适应。