Justin Valdez
Justin Valdez

Reputation: 47

How can I delete the proper object property value in JS

I am working through a little practice assignment and have come across this question and for the life of me can't figure it out. There are tests parameters that I can't see. The object is not a variable I can see, it's just assumed.

Write a function called removePassword that takes in an object. Delete the property password and return the object.

removePassword=(object)=>{
for(var key in object){
  if(object = object[key]){
  delete object[key]
    }
  }return object;
}

I have tried a bunch of different versions of this code, but I don't know how to just delete the property password only without deleting the other property which is a username

Upvotes: 1

Views: 376

Answers (3)

Francesco Cipolla
Francesco Cipolla

Reputation: 73

Take a look at this solution. You can avoid doing the object copy if you want, it'll work anyway

const removePassword = (user) => {
  const userCopy = {...user} // CREATE A COPY OF THE OBJECT
  delete userCopy.password // DELETE THE PASSWORD PROPERTY
  return userCopy // RETURN UPDATED USER
}

const testUser = {username: 'Mario', password: 'supersecret123'}

console.log(
  removePassword(testUser)
)

Upvotes: 2

Sowam
Sowam

Reputation: 1736

You can see here link

That you can do it simply delete object.password or delete object["password"] :

const removePassword = (object) => {
  delete object.password;
  return object;
}

Upvotes: 1

Welyngton Dal Pra
Welyngton Dal Pra

Reputation: 774

Could it work for you?

removePassword = (object) => {
  delete object.password;
  return object;
}

Upvotes: 1

Related Questions