Delete object property javascript not working

Delete Object Not Working With Code Examples

With this article, we’ll look at some examples of Delete Object Not Working problems in programming.

// define dis-allowed keys and values
const disAllowedKeys = ['_id','__v','password'];
const disAllowedValues = [null, undefined, ''];

// our object, maybe a Mongoose model, or some API response
const someObject = {
  _id: 132456789,
  password: '$1$O3JMY.Tw$AdLnLjQ/5jXF9.MTp3gHv/',
  name: 'John Edward',
  age: 29,
  favoriteFood: null
}; 

// use reduce to create a new object with everything EXCEPT our dis-allowed keys and values!
const withOnlyGoodValues = Object.entries(someObject).reduce((ourNewObject, pair) => {
  const key = pair[0];
  const value = pair[1]; 
  if (
    disAllowedKeys.includes(key) === false &&
    disAllowedValues.includes(value) === false
  ){
    ourNewObject[key] = value; 
  }
  return ourNewObject; 
}, {}); 

// what we get back...
// {
//   name: 'John Edward',
//   age: 29
// }

// do something with the new object!
server.sendToClient(withOnlyGoodValues);

As we have seen, the Delete Object Not Working problem was solved by using a number of different instances.

Can not delete property of object?

You can only delete a Property or Method of an object using the Delete Operator. It will completely remove the Property from the collection. It also does not remove the Non-configurable properties. Delete returns false if the property is an own property and cannot be deleted.

How do you delete an object?

Right-click over the objects you want to delete, and choose Delete. In the Delete dialog box, select the objects you want to delete from the list.

How do you delete an object in C++?

In C++, the single object of the class which is created at runtime using a new operator is deleted by using the delete operator, while the array of objects is deleted using the delete[] operator so that it cannot lead to a memory leak.18-Jan-2021

How do you delete an object in node JS?

The only way to fully remove the properties of an object in JavaScript is by using delete operator. If the property which you’re trying to delete doesn’t exist, delete won’t have any effect and can return true.06-Feb-2020

How do you delete an object in Java?

You can delete an object in Java by removing the reference to it by assigning null. After that, it will be automatically deleted by the Garbage Collector.

How do you delete an object from an array?

There are different methods and techniques you can use to remove elements from JavaScript arrays:

  • pop – Removes from the End of an Array.
  • shift – Removes from the beginning of an Array.
  • splice – removes from a specific Array index.
  • filter – allows you to programatically remove elements from an Array.

How do I remove a property from an object?

Remove Property from an Object The delete operator deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions.

How do I remove an object from a bucket?

In the Buckets list, choose the name of the bucket that you want to delete an object from. Select the check box to the left of the names of the objects that you want to delete. Choose Actions and choose Delete from the list of options that appears. Alternatively, choose Delete from the options in the upper right.

What is delete operator in oops?

Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression. Delete can be used by either using Delete operator or Delete [ ] operator. New operator is used for dynamic memory allocation which puts variables on heap memory.13-Oct-2021

Can we do delete this in C++?

Answer: Yes, we can delete “this” pointer inside a member function only if the function call is made by the class object that has been created dynamically i.e. using “new” keyword.24-May-2015

Questions : Javascript delete object property not working

2022-09-10T20:37:14+00:00 2022-09-10T20:37:14+00:00

985

I'm running some project on MEAN.js and I've anycodings_mean-stack got a following problem. I want to make some anycodings_mean-stack user's profile calculation and the save it anycodings_mean-stack to database. But there's a problem with anycodings_mean-stack method in users model:

UserSchema.pre('save', function(next) {
    if (this.password && this.password.length > 6) {
        this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
        this.password = this.hashPassword(this.password);
    }
    next();
});

If I will send a password with my changes, anycodings_mean-stack it will change credentials, so user is anycodings_mean-stack unable to login next time. I want to delete anycodings_mean-stack password from user object before save, but anycodings_mean-stack I'm not able to do it (let's look at the anycodings_mean-stack comments in my code below):

exports.signin = function(req, res, next) {
    passport.authenticate('local', function(err, user, info) {
        if (err || !user) {
            res.status(400).send(info);
        } else {
            /* Some calculations and user's object changes */
            req.login(user, function(err) {
                if(err) {
                    res.status(400).send(err);
                } else {
                    console.log(delete user.password); // returns true
                    console.log(user.password); // still returns password :(
                    //user.save();
                    //res.json(user);
                }
            });
        }
    })(req, res, next);
};

What's wrong? Why the delete method returns anycodings_mean-stack true, but nothing happens? Thanks for your anycodings_mean-stack help :)

Total Answers 6

33

Answers 1 : of Javascript delete object property not working

Just do:

user.password = undefined;

instead of:

delete user.password;

and the password property will not anycodings_javascript appear at the output.

0

2022-09-10T20:37:14+00:00 2022-09-10T20:37:14+00:00Answer Link

mRahman

2

Answers 2 : of Javascript delete object property not working

there are certain rules for delete anycodings_javascript 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 anycodings_javascript for more information your can read this anycodings_javascript Link

0

2022-09-10T20:37:14+00:00 2022-09-10T20:37:14+00:00Answer Link

miraj

6

Answers 3 : of Javascript delete object property not working

Had a similar problem. This worked for anycodings_javascript me:

// create a new copy  
let newUser= ({...user}._doc); 

// delete the copy and use newUser that thereafter. 
delete newUser.password; 

0

2022-09-10T20:37:14+00:00 2022-09-10T20:37:14+00:00Answer Link

miraj

2

Answers 4 : of Javascript delete object property not working

Working with MONGOOSE?

If you're facing this issue when working anycodings_javascript with Mongoose (Mongo DB's upper layer) anycodings_javascript then you can use lean property on find anycodings_javascript method

Examples

Without lean (The keys won't be deleted)

const users = await User.find({ role: 'user' }) // no lean method
   users.forEach((user) => {
   delete user.password.  // doesn't delete the password
})

console.log(users) 

/* [
    {name:'John', password:'123'}, 
    {name:'Susan', password:'456'}
   ] 
*/ 

With lean (The keys get deleted)

const users = await User.find({ role: 'user' }).lean() 
   users.forEach((user) => {
   delete user.password   // deletes the password
})

console.log(users) 

/* [
    {name:'John'}, 
    {name:'Susan'}
   ] 
*/ 

Reason why lean works

Documents returned from queries with the anycodings_javascript lean option enabled are plain javascript anycodings_javascript objects, not Mongoose Documents. They anycodings_javascript have no save method, getters/setters, anycodings_javascript virtuals, or other Mongoose features.

Documents are kind of read-only, so anycodings_javascript delete doesn't work on them

Reference - anycodings_javascript https://stackoverflow.com/a/48137096/10824697 https://mongoosejs.com/docs/api.html#query_Query-lean

Method 2 without lean

If you want to use the mongoose provided anycodings_javascript method to remove some property while you anycodings_javascript are querying, you can remove with select anycodings_javascript method,

const users = await User.find({ role: 'user' }).select('-password')

console.log(users)
 /* [
      {name:'John'}, 
      {name:'Susan'}
    ] 
 */ 

0

2022-09-10T20:37:14+00:00 2022-09-10T20:37:14+00:00Answer Link

raja

3

Answers 5 : of Javascript delete object property not working

The answer above from Majed A is the anycodings_javascript simplest solution that works for single anycodings_javascript objects properties, we can even make it anycodings_javascript for more easier by removing the ...user anycodings_javascript spreader. just delete the property from anycodings_javascript your object._doc sub-object. in your anycodings_javascript 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

2022-09-10T20:37:14+00:00 2022-09-10T20:37:14+00:00Answer Link

jidam

2

Answers 6 : of Javascript delete object property not working

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

_.unset(user, "password");

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

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

0

2022-09-10T20:37:14+00:00 2022-09-10T20:37:14+00:00Answer Link

joy

Top

  • © 2022 ANYCODINGS.COM - All Rights Reserved.
  • About Us
  • Contact Us
  • DMCA
  • Privacy Policy
  • Disclaimer
  • Terms & Conditions

Can not delete property of object?

You can only delete a Property or Method of an object using the Delete Operator. It will completely remove the Property from the collection. It also does not remove the Non-configurable properties. Delete returns false if the property is an own property and cannot be deleted.

How do we delete the object property in JavaScript?

The delete operator deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions.

Which is the correct way to remove property from an object?

The semantically correct way to remove a property from an object is to use the delete keyword.

Which keyword is used for deleting properties on objects?

delete keyword is used to delete properties of an object in javaScript.