How to conditionally add properties to an object
Daisho Komiyama edited this page Apr 26, 2023
·
1 revision
In JavaScript, you can conditionally add properties to an object using a simple syntax.
const user = {
name: 'me',
email: 'me@me'
}
const newUser = {
...(user.name && { name: user.name }), // add `name` property with the value if `user` has `name` property
email: user.email
}
console.log(newUser)
// output: { name: 'me', email: 'me@me' }
const anotherUser = {
...(user.secret && { secret: user.secret }),
email: user.email
}
console.log(anotherUser)
// output: { email: 'me@me' }
This simple yet powerful technique can come in handy when working with objects.