4

I need to know if a JavaScript object contains a certain variable.

EG: Check if 'map' contains 'here'

var map = {
    '10': '0',
    '20': '0',
    '30': 'here',
    },

2 Answers 2

4

You have to loop through the object to test it:

var chk = false;
for(var key in map){
    if(map[key] == "here"){
        chk = true;
        break;
    }
}
alert(chk?"Yup":"Nah");

You can also put this in Object prototype:

Object.prototype.ifExist = function(txt){
    var chk = false;
    for(var key in this){
        if(this[key] == txt){
            chk = true;
            break;
        }
    }
    return chk;
}

//map.ifExist("here");
//return true

Demo: http://jsfiddle.net/DerekL/yWnYy/

Sign up to request clarification or add additional context in comments.

Comments

1

You'll have to iterate over the object using the for..in syntax:

function in_object(value, object) {
    for (var key in map) {
        if (map[key] == value) {
            return true;
        }
    }

    return false;
}

Here's an example:

> in_object('heres', map)
false
> in_object('here', map)
true

Comments

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.