1

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?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Ilja
  • 44,142
  • 92
  • 275
  • 498
  • 1
    Why not assign the common values first, then just add the additional ones later. `var data = {name: 'String'}; if(something){ data.something = 'Something'; }`? – gen_Eric Jun 01 '16 at 15:27
  • Simplest way is to let data = {}; and then in your if, just do data.name='String'; data.something = 'Something' etc etc But there are tons of ways to skin this cat. – Tad Donaghe Jun 01 '16 at 15:27
  • 2
    There is no such thing as a [JSON object](http://stackoverflow.com/q/2904131/1048572). And what you have here isn't JSON anyway (lacking quotes). – Bergi Jun 01 '16 at 15:31

3 Answers3

3

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';
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Of course, but there's something vaguely unsatisfying about this. –  Jun 01 '16 at 16:04
  • @torazaburo: The repetition of the identifier `data` maybe? I like your approach, but for some reason I probably still wouldn't use it. – Bergi Jun 01 '16 at 16:11
0

you can use can a ternary operator like this:

let data = {
  name: 'String',
  something: (something) ? "Something" : undefined,
}

practically this should work because undefined is what you get when trying to access a non-existing object property,
but keep in mind you're adding an enumerable property to the object.

maioman
  • 18,154
  • 4
  • 36
  • 42
0

You can use Object.assign as follows, because it ignores non-object parameters:

let data
let something = true
data = Object.assign(
    { name: 'String' },
    something && {something: 'Something'}
)

console.log(data)

Or, if you prefer

something ? {something: 'Something'} : {}