How do I remove a key from a JavaScript object?

This question already has an answer here:

  • How do I remove a property from a JavaScript object? 33 answers

  • The delete operator allows you to remove a property from an object.

    The following examples all do the same thing.

    // Example 1
    var key = "Cow";
    delete thisIsObject[key]; 
    
    // Example 2
    delete thisIsObject["Cow"];
    
    // Example 3
    delete thisIsObject.Cow;
    

    If you're interested, read Understanding Delete for an in-depth explanation.


    If you are using Underscore.js or Lodash, there is a function 'omit' that will do it.
    http://underscorejs.org/#omit

    var thisIsObject= {
        'Cow' : 'Moo',
        'Cat' : 'Meow',
        'Dog' : 'Bark'
    };
    _.omit(thisIsObject,'Cow'); //It will return a new object
    
    => {'Cat' : 'Meow', 'Dog' : 'Bark'}  //result
    

    If you want to modify the current object, assign the returning object to the current object.

    thisIsObject = _.omit(thisIsObject,'Cow');
    

    With pure JavaScript, use:

    delete thisIsObject['Cow'];
    

    Another option with pure JavaScript.

    thisIsObject.cow = undefined;
    
    thisIsObject = JSON.parse(JSON.stringify(thisIsObject ));
    

    如果您使用的是JavaScript外壳,那么这很简单:

    delete object.keyname;
    
    链接地址: http://www.djcxy.com/p/4660.html

    上一篇: 如何从JavaScript对象中删除项目

    下一篇: 我如何从JavaScript对象中移除一个键?