0

I'm trying to check a value in JS that on page load is returned as a single-element array and after an ajax function returns as a string. I don't know why it's doing this but I'm trying to role with it.

So, using console.log(value) I get array ['Scranton'] on page load, and the ajax even returns string "Scranton"

When trying to check this variable, this does not work as I intended:

if ( value === 'Scranton' || value === ['Scranton']){
    ...
}

Any help is appreciated!

psorensen
  • 809
  • 4
  • 17
  • 33

4 Answers4

3

This would probably work but I would try and fix the underlying issue instead of working around it.

if ( value === 'Scranton' || value[0] === 'Scranton'){
    ...
}
Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
2

You can use indexOf for both an array and a string, so value.indexOf("Scranton") !== -1 will work (just tested this on the console).

However you must first check for null/false/undefined or it will error.

if (value && value.indexOf("Scranton") !== -1) {}

EDIT: As Felix said, this will also be true for any string containing "Scranton". If this is a problem, then you can check for indexOf == 0 instead, which will be true for any string starting with "Scranton". It really depends on your concrete problem if this solution fits you. Use with care.

Pablo Mescher
  • 26,057
  • 6
  • 30
  • 33
1
if (Object.prototype.toString.call(value) === '[object Array]') {
    if (value.indexOf('Scranton') != -1) {
        /*  */
    }
} else {
    if (value === 'Scranton') {
        /*  */
    }
}

Edit 1:

First, you need to check if "value" is an array. If it's an array and contains the string "Scranton", you can find it using value.indexOf(). And if "value" is not an array, you can directly compare it with the string 'Scranton'.

riovel
  • 86
  • 4
0

What does "after an ajax function" mean? The page loads with a default variable that has been assigned an array value, and then an Ajax request is made, which changes this default variable, and instead of an array being assigned, it assigns a string? Assuming this "ajax function" changes the default variable to the response text from the server, there is your problem: Ajax--like any other request--is text-based, so it is a string. If you are responding to the Ajax request with a JSON string, built on the server, it needs to be parsed in the browser, so it can be reinterpreted as an array. See the JSON.parse method.

danemacmillan
  • 1,202
  • 12
  • 13