0

I am trying to find if an object contains a certain value and then have that dictate the next steps of the operation. This is an object that is returned from Google Maps API. This is an exact example returned back from their API.

Array

[{'long_name': 'United States', 'short_name': 'US'}, {'long_name': 'California', 'short_name': 'CA'}];

Conditional/Check

if( $.inArray('US', array) == -1 ){

    alert('Your country is not supported.');

} else {
     alert('Your country is supported.');   
}

This doesn't work because it only looks at the index, and not values I believe. What's the cleanest and fastest way to find and return if the value exists in the array?

20
  • 6
    array is an object, not an array. Commented Apr 17, 2015 at 0:25
  • @FelixKling and js arrays are objects! Commented Apr 17, 2015 at 0:25
  • 2
    Actually, it's not even an object, it's a syntax error Commented Apr 17, 2015 at 0:27
  • 2
    @JoshuaByer: Please don't call an object "hash array", it just adds to the confusion. JS has objects and arrays are a special kind of object. Commented Apr 17, 2015 at 0:33
  • 3
    @Interrobang well, they don't "have to be", strictly speaking it's a syntactically valid expression. I wouldn't say "invalid" to not confuse anyone (since that's not true) Commented Apr 17, 2015 at 0:40

2 Answers 2

5

To find a match you could use jQuery.grep():

var res = $.grep(arr, function(item) {
    return item.short_name == 'US';
});

It returns an array, which will be empty if there are no matches found.

Alternatively, you could use Array.prototype.filter():

var res = arr.filter(function(item) {
    return item.short_name == 'US';
});

Bonus

You can generalise it further:

function searchFunction(field)
{
    return function(arr, term) {
        return arr.filter(function(item) {
            return item[field] == term;
        };
    };
}

var searchByShortName = searchFunction('short_name');

if (searchByShortName(arr, 'US').length) {
    // ..
}
Sign up to request clarification or add additional context in comments.

1 Comment

Very elegant. I appreciate your time on this very educational answer. I was a little unclear in my question and I do apologize. Thank you very much!
1

What you need is something like this

var countries = [{'long_name': 'United States', 'short_name': 'US'},
{ 'long_name': 'California', 'short_name': 'CA'}]; //now this is an array with objects

function hasCountry(shortName){
    for(var i = 0, len = countries.length; i < len; i++){
        if(countries[i]['short_name'] === shortName) return true;
    }
    return false;
}

if(hasCountry('US')){
   // not supported..
} else {
   // not supported
}

However, a better solution would be normalize the countries to an object like this.

var countries = {'US': 'United States', 'CA': 'California'}; // this is an object

if(countries['US'] != null){
    // supported
} else {
  // not supported
}

1 Comment

1. syntax error (see syntax highlights) 2. It would be much better if hasCountry accepted both an array and a search term.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.