Sometimes we need to add to an object a variable which can contain value or be undefined.
const city = undefined // can be string or undefined
const person = {
name: 'Harry',
}
In JavaScript we can do it easily, just by writing the variable name inside an object. But it has one problem. Now the object has two keys despite this variable being undefined.
const person = {
name: 'Harry',
city,
}
console.log(person) // { name: 'Harry', city: undefined }
console.log(Object.keys(person)) // [ 'name', 'city' ]
Of course we can check it manually in an if block and add it only if it contains a value.
const person = {
name: 'Harry',
}
if (city) {
person.city = city
}
But I will show you a more elegant way.
We can use a mix of the spread operator and ternary operator inside an object. If the variable has data we merge the object with the needed variable, if not we merge an empty object, so the object remains clear.
const city = undefined // can be string or undefined
const person = {
name: 'Harry',
...(city ? {city} : {}),
}
console.log(person) // { name: 'Harry' }
console.log(Object.keys(person)) // [ 'name' ]
Subscribe to know more tips about JavaScript.
Top comments (0)