0

I'm using AJAX to retrieve data via php. The resulting object available to Jquery looks like this:

Object {1234: "Martin", 4567: "Alf", 8512: "Symon"}

using the following I can get the key:

if ('4567' in staff)
    console.log('found')

How would I check if Alf exists ?

I've tried inArray, indexOf and various other examples, but I've not managed to get this working.

Thanks

Rocket
  • 1,065
  • 2
  • 21
  • 44
  • 1
    Possible duplicate of [How to check if value exists in object using javascript](http://stackoverflow.com/questions/35948669/how-to-check-if-value-exists-in-object-using-javascript) – Andrew Li Mar 12 '17 at 17:13
  • The only way you can do that is loop through the values of Object and find if it has the value. Unless you want to use ES7 – Imprfectluck Mar 12 '17 at 17:15
  • Possible duplicate of [How do I check if an object has a property in JavaScript?](http://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-a-property-in-javascript) – technophobia Mar 12 '17 at 17:55

1 Answers1

2

Use JavaScript reflection as following:

var obj = {1234: "Martin", 4567: "Alf", 8512: "Symon"};

var find = function(input, target){
    var found;
    for (var prop in input) {
    if(input[prop] == target){
        found = prop;
    }
    };

    return found;
};

var found = find(obj, 'Alf');

if(found){
    alert(found);
}

https://jsfiddle.net/8oheqd3j/

Mohammad Akbari
  • 4,486
  • 6
  • 43
  • 74