Javascript delete object property not working

后端 未结 5 1723
难免孤独
难免孤独 2021-01-01 13:31

I\'m running some project on MEAN.js and I\'ve got a following problem. I want to make some user\'s profile calculation and the save it to database. But there\'s a problem w

相关标签:
5条回答
  • 2021-01-01 14:03

    Just do:

    user.password = undefined;
    

    instead of:

    delete user.password;
    

    and the password property will not appear at the output.

    0 讨论(0)
  • 2021-01-01 14:05

    Had a similar problem. This worked for me:

    // create a new copy  
    let newUser= ({...user}._doc); 
    
    // delete the copy and use newUser that thereafter. 
    delete newUser.password; 
    
    
    0 讨论(0)
  • 2021-01-01 14:14

    there are certain rules for delete operator in javascript

    1. if the property is an own non-configurable property in "strict mode" than it will return false.

    for example

    x = 42;         // creates the property x on the global object
    var y = 43;     // creates the property y on the global object, and marks it as non-configurable
    
    // x is a property of the global object and can be deleted
    delete x;       // returns true
    
    // y is not configurable, so it cannot be deleted                
    delete y;       // returns false 
    
    1. If the object inherits a property from a prototype, and doesn't have the property itself, the property can't be deleted by referencing the object. You can, however, delete it directly on the prototype.

    for example

    function Foo(){}
    Foo.prototype.bar = 42;
    var foo = new Foo();
    
    // returns true, but with no effect, 
    // since bar is an inherited property
    delete foo.bar;           
    
    // logs 42, property still inherited
    console.log(foo.bar);
    

    so, please cross check these point and for more information your can read this Link

    0 讨论(0)
  • 2021-01-01 14:14

    Had a similar issue. The delete operator "was not working" when trying to delete a property from an object in a specific case. Fixed it using Lodash unset:

    _.unset(user, "password");

    https://lodash.com/docs/4.17.11#unset

    Otherwise the delete operator does work. Just in case, delete operator docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

    0 讨论(0)
  • 2021-01-01 14:21

    The answer above from Majed A is the simplest solution that works for single objects properties, we can even make it for more easier by removing the ...user spreader. just delete the property from your object._doc sub-object. in your example it would have been:

    user.save()
    delete user._doc.password
    res.status(201).json(user) // The password will not be shown in JSON but it has been saved.
    
    0 讨论(0)
提交回复
热议问题