How to conditionally pass a key to a javascript Object
Javascript Object is an unordered collection of key and value pairs, these key and value pairs are called a property. The key can be a string and the value of the property can be any value.
There could be an instance where you only want to pass a key to an object only when it has a value so as not to encounter an error for instance when interacting with an api.
Scenario: You have an api that expects a payload of:
{
name: "Micheal"
email: "micheal@micheal.co"
phone: "+23400000000"
blog_site: "https://michellead.hasnode.dev"
}
for some reason, if your blog_site
value is null and you want to omit it, here is a way to go about it:
const personDetails = {
name: "Micheal",
email: "micheal@micheal.co",
phone: "+23400000000",
blog_site: null
}
const payload = {
name: personDetails.name,
email: personDetails.email,
phone: personDetails.phone,
...(personDetails.blog_site && {
blog_site: personDetails.blog_site
})
};
console.log(payload) //{ name: 'Micheal', email: 'micheal@micheal.co', phone: '+23400000000' }
The above checks if the personDetails.blog_site
key has a value which is null
or undefined
and removes it from the payload.
I hope with this, you can see how the conditionally pass a key and value pair to an object. Thanks for reading! ๐
Subscribe to my newsletter
Read articles from Micheal Adisa directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Micheal Adisa
Micheal Adisa
I am a software engineer and technical writer with experience in crafting great products. I craft products with excellent user experience.