0

I have a weird javascript issue. I am using vue js and axios to get some data from an API. I have dumped console.log and the values are there but my if statement will not be true.

Removed stuff so the code example is smaller.

See inline comments.

HTML:

<input v-model="system_id">
<button v-on:click="getSystemData" class="btn btn-primary">Get system data</button>


Data model:

data: () => ({
  errors: [],
  system_id: null,
  system_data: null
}),



Function:

getSystemData () {
    HTTP.get('/api/get_systems')
    .then(response => {
      this.response = response.data

      // equals 1234
      console.log(this.system_id)
      for (var key in this.response) {

        // the id 1234 is found here in a large list
        console.log(this.response[key].system_id)


        // Does not go true?!?!
        if (this.response[key].system_id === this.system_id) {
          this.system_data = this.response[key].system_data
        }
      }
    })
    .catch(e => {
      this.errors.push(e)
    })
  }

Why does the if never trigger??

John
  • 1,243
  • 4
  • 15
  • 34
  • First of all I would make sure that the statement is actually true. For instance by putting a debugger in the line before. Or how otherwise did you proof yourself if the statement is ever true? – trueunlessfalse May 28 '17 at 13:29
  • what is the type for `this.system_id` ? https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons – Suraj Rao May 28 '17 at 13:30
  • Try with `==` instead of `===`. The `===` operator checks value and type. I don't know your case, but maybe your values have different types, e.g. `number` and `string`? – mingos May 28 '17 at 13:30
  • Possible duplicate of [Which equals operator (== vs ===) should be used in JavaScript comparisons?](https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons) – Suraj Rao May 28 '17 at 13:35

1 Answers1

2

The problem maybe with mismatch datatypes. === operator will return false for if(1234==="1234"). Use == operator

Vipul Jain
  • 94
  • 1
  • 4
  • 2
    For the sake of understanding what went wrong, I'd still recommend to use debugger, look at how the types are different, and try to understand why. Then you can consciously decide to use == here, which in other situations might be a bad choice. – trueunlessfalse May 28 '17 at 13:39
  • Yes it was string vs integer comparison. I had to use: if (this.response[key].system_id === Number(this.system_id)) ... using == eslint complained. – John May 28 '17 at 13:53