DEV Community

Cover image for JS πŸ”₯: Conditionally setting an object property
Benjamin Mock
Benjamin Mock

Posted on • Originally published at codesnacks.net

JS πŸ”₯: Conditionally setting an object property

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)