Search code examples
javascriptobject

javascript check to see if value matches object


I have a javascript object

var obj = {
    "0" : "apple",
    "1" : "pear",
    "2" : "orange"
}

I want to check if 'orange' is in obj.

Is there a built in function that does this? Or should I iterate over each value of obj?

Thanks.


Solution

  • You'll have to iterate:

    for (var k in obj) {
      if (!obj.hasOwnProperty(k)) continue;
      if (obj[k] === "orange") {
        /* yaay! an orange! */
      }
    }
    

    Now that "hasOwnProperty" test in there is to make sure you don't stumble over properties inherited from the prototype. That might not be desirable in some cases, and really it's one of the things you kind-of need to understand in order to know for sure whether you do or don't want to make that test. Properties that you pick up from an object's prototype can sometimes be things dropped there by various libraries. (I think the ES5 standard provides for ways to control whether such properties are "iterable", but in the real world there's still IE7.)