1

I want to set some keys in object depending on flag value

For example

const ourFlag = true //true or false depends on case

const ourObject = {
  name: 'Pablo',
  secondName: 'Picasso',
  [ourFlag && 'age']: 20,
  [ourFlag && 'moreComplexValue']: [
    {
      val: true
    },
    {
      val: false
    }
  ]
}

As long as ourFlag is set to true everything works as I expected, but when I change it's value to false some weird things started to come.

property age is no longer present - good but property moreComplexValue is now false

Code I get when flag is false:

{
  name: 'Pablo',
  secondName: 'Picasso',
            // age disappear as I expected
  false: [  //why!?!
    {
      val: true
    },
    {
      val: false
    }
  ]
}

Code I get when flag is true:

{ .    //brilliant everything is fine
  name: 'Pablo',
  secondName: 'Picasso',
  age: 20,
  moreComplexValue: [
    {
      val: true
    },
    {
      val: false
    }
  ]
}

It's any way to handle it with that computed properties?

Paul
  • 296
  • 1
  • 4
  • 16
  • Does this answer your question? [Assign, and set js object property conditionally](https://stackoverflow.com/questions/50367085/assign-and-set-js-object-property-conditionally) – Bilal Siddiqui Oct 31 '19 at 13:00

2 Answers2

5

[flag && key] evaluates to false or key, and this is exactly what your literal does, converting false to a string and overwriting it when the flag is false.

A better option would be to use an object spread ...flag && object, which will expand to the object in the true case, and to an empty Boolean in the false case, thus essentially skipping it.

let ourFlag = true

const a = {
    name: 'Pablo',
    secondName: 'Picasso',
    ...ourFlag && {age: 20},
    ...ourFlag && {moreComplexValue: [1, 2, 3]}
}

ourFlag = false


const b = {
    name: 'Pablo',
    secondName: 'Picasso',
    ...ourFlag && {age: 20},
    ...ourFlag && {moreComplexValue: [1, 2, 3]}
}

console.log(a)
console.log(b)
georg
  • 211,518
  • 52
  • 313
  • 390
1

The problem is the javascript object keys are always strings and are typecasted to strings when otherwise.

So, it becomes string "false" when the value is false and the same key is used twice and rewritten with the second value

To set the keys dynamically, you could set it to undefined or set it with if..else

const ourFlag = true //true or false depends on case

const ourObject = {
  name: 'Pablo',
  secondName: 'Picasso',
}
if(ourFlag) {
  ourObject.age = 20;
  ourObject.moreComplexValue = [
    {
      val: true
    },
    {
      val: false
    }
  ];
}
Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25