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.
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.
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);
Browser other questions tagged javascript
You are not signed in. Login or sign up in order to post.
Hmmm, I get it. But is there any right way?? Or is there no right way to do it??
– fernandoocf
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.– BrTkCa
A friend told me to do "person.age = Undefined". Is that right?? It could bring some problem?
– fernandoocf
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.– BrTkCa
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).
– bfavaretto
@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.
– bfavaretto
Thank you! @bfavaretto
– fernandoocf