0

If I have the following code written where i'm trying to interchange between failedIds and passedIds:

hideShowTestResults: function(failOrPass){
    if(this.[failOrPass ? passedIds : failedIds ].length > 0){} 
}

Yet this syntax is not accepted in JS, how would I go about this?

Thanks, Bud

senseCode
  • 3
  • 5

1 Answers1

6
  • bracketed property access looks like obj[prop], not obj.[prop]

  • the property name is an expression that produces a string

if (this[failOrPass ? 'passedIds' : 'failedIds'].length > 0) {

Or, because selecting a property name is kind of less readable than selecting an array:

if ((failOrPass ? this.passedIds : this.failedIds).length > 0) {
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • This seems like a weird function, though. It might be better as two or more functions. – Ry- Dec 05 '19 at 15:10
  • Noting that it'd be more readable, and reduce cognitive overhead, to pull this out into two statements. – Dave Newton Dec 05 '19 at 15:11
  • 1
    I just did now : `let result = failOrPass ? this.passedIds : this.failedIds;` and then: `if(result.length > 0){}` but you answer is well invested, so i'll vote it soon when it allows – senseCode Dec 05 '19 at 15:13