DEV Community

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

Posted on β€’ Originally published at codesnacks.net

25 4

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’