Search code examples
javascriptobject-literal

Constructing object based on true/false conditions


I am usually constructing objects that do have fields in them or do not have them based on a condition so

let data
if(something === true) {
  data = {
    name: 'String',
    something: 'Something'
  }
else {
  data = {
    name: 'String'
  }
}

but this seems like a very "dirty way to do this" as data needs to be redefined every time + if there were more if conditions this would become quiet big chunk of code. Is there a more concise way to achieve this?


Solution

  • Just conditionally add properties to the object - you don't need to define the whole thing in one go as an object literal.

    let data = {
        name: 'String'
    };
    if (something) {
        data.something = 'Something';
    }