Rocket
Rocket

Reputation: 1093

Jquery Check for key or value in array object

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

Upvotes: 0

Views: 4642

Answers (1)

Mohammad Akbari
Mohammad Akbari

Reputation: 4766

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/

Upvotes: 2

Related Questions