Want to get better at Web Development πππ? Subscribe to my weekly newsletter at https://codesnacks.net/subscribe/
Let's assume we only want to add an object property if some condition is true. We can do this using an if-statement of course:
const someCondition = true;
const anotherCondition = false;
const myObject = {
name: "codesnacks",
};
if(someCondition){
myObject.author = "Ben";
}
if(anotherCondition){
myObject.platform = "dev.to";
}
console.log(myObject); // {name: "codesnacks", author: "Ben"}
We can achieve the same using the object spread operator ( ...
) in combination with the condition when creating the object. No additional if-statement is needed. This is especially elegant if an object has multiple conditional properties.
const someCondition = true;
const anotherCondition = false;
const myObject = {
name: "codesnacks",
...(someCondition && { author: "Ben" }),
...(anotherCondition && { platform: "dev.to" }),
};
console.log(myObject); // {name: "codesnacks", author: "Ben"}
Want to get better at Web Development?
πππsubscribe to the Tutorial Tuesday βοΈnewsletter
Top comments (0)