links: JS MOC
How to build an object conditionally?
Let’s consider a scenario where you want to search the github issues. In order to that whenever you choose a option that will be reflected as query params in the url something like this https://github.com/react-native-clipboard/clipboard/issues?q=is_open=true&is_issue=true&label=bug
One way is
let queryParams = {}
if(isOpen) {
queryParams["is_open"] = isOpen
}
if(is_issue) {
queryParams["is_issue"] = isIssue
}
if(label) {
queryParams["label"] = label
}This way you can build the object for query params. What if you can build it with less code using conditional object spread
let queryParams = {
...(isOpen && {"is_open": isOpen}),
...(isIssue && {"is_issue": isIssue}),
...(label && {"label": label})
}The gist of it is
const x = {
...(true && {name: 'chakri'}),
...(false && {age: 26})
}
console.log(x) // {name: "chakri"}The truthy values get spread to the object and falsy values are ignored
Fun fact
console.log({...(null)}) // {}
console.log({...(undefined)}) // {}
console.log({...(2)}) // {}
console.log({...('hello')}) // {0: "h", 1: "e", 2: "l", 3: "l", 4: "o"}tags: javascript , object