2
I would like to know how to add conditional properties to a literal object in the leanest way possible.
I currently declare the object and then add the conditional properties as in the following example:
function getFamilia(avos) {
const familia = {
filhos: ['Pedro', 'Claudia'],
pais: ['Marcio', 'Fernanda']
}
if (avos) {
familia.avos = avos
}
return familia
}
I have tried to make a ternary in the definition of the object but the key remains there even if it returns Undefined. Example:
const getFamilia = avos => ({
filhos: ['Pedro', 'Claudia'],
pais: ['Marcio', 'Fernanda'],
avos: avos || undefined
})
Is there any way to make conditional directly in the object declaration without leaving the key there in the false case?
You can use any feature of any javascript version.
I can’t understand at all, um... what you want is that property
'avos'
does not exist?– Klaider
Exact @Matheus. If she has a value she wanted the object to have the property filled. If not, she wanted it not to exist in the object.
– Leandro Oriente