Doubt to remove Javascript attributes

Asked

Viewed 696 times

2

Given the following object:

var pessoa = {
    nome: 'Fernando',
    idade: 15,
}

I would like to know the most RIGHT way (if there is a more correct way) to remove one of these attributes.

1 answer

6


You can use the delete operator:

var pessoa = {
    nome: 'Fernando',
    idade: 15,
};

// verifica se nome existe
if (pessoa.nome)
 delete pessoa.nome;

console.log(pessoa);

  • Hmmm, I get it. But is there any right way?? Or is there no right way to do it??

  • I don’t know any other way to remove a key from an object other than delete. If you are unsure when the key exists, it would be interesting to use pessoa['nome'];. This is the standard form.

  • A friend told me to do "person.age = Undefined". Is that right?? It could bring some problem?

  • This is to check if the attribute exists. If you want to check if it exists before deleting for example, it is possible to do: if (pessoa.idade) delete pessoa.idade. What happens here is that it will only delete if it exists.

  • 1

    You don’t even need to check if it exists, delete will only launch exception if the property is not deleteable (and yet only custom, non-native properties).

  • @fernandoocf Your friend told you to change the value of the property to Undefined. This is different from removing the object property, only removes the value.

  • Thank you! @bfavaretto

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.