jfoutch
jfoutch

Reputation: 1398

Return value for a specific key in javascript?

I have an object with numbers as keys and image paths as values. I am getting numbers from a combination of selected radio buttons. Such as 1111 or 2111 if the first radio buttons in each group are all selected or the second radio then all first. I want to search the object for a key of 1111 then if it exists, return its value, which would be an image path. I can successfully find if the object has a matching key, but how do I return the value for that key only? In the case of 1111 I would need to return "my/image/path1". Here is what I have so far:

    var array = [];
var imgs = {
    1111: "my/image/path1",
    2111: "my/image/path2",
    1211: "my/image/path3",
    1311: "my/image/path4"
}

$(':radio').change(function() {
    $(":radio:checked").each(function(i, e)  {
    array[i] = $(this).val();
    });
        var total = 0;
        $.each(array,function() {
            total += this;
        });
        matchKey = parseInt(total, 10);
         // here is where I'm stuck
        if (imgs contains the key matchKey)) {
            console.log(value for matchKey);
        }

});

Upvotes: 0

Views: 1576

Answers (4)

Jamiec
Jamiec

Reputation: 136074

You can use square-bracket notation

if (imgs[matchKey]) {
    console.log(imgs[matchKey]);
}

Note: This assumes none of your values will ever be falsey (eg, 0, a blank string, false etc). Which I think is fine, as you said your values are always non-empty paths. But the warning stands. If your values could legitimately be falsy, check @Florian answer.

Upvotes: 2

MHardwick
MHardwick

Reputation: 644

You can use Object.keys(imgs) to retrieve an array of just the keys, and then perform a simple test to see if the key you're looking for is contained in the array:

if (Object.keys(imgs).indexOf('1111') > -1)

Upvotes: 0

Florian
Florian

Reputation: 712

In your case you can use plain javascript:

if (typeof imgs[matchKey] !== "undefined") { // Check if the key exists
    var value = imgs[matchKey];
}

Upvotes: 2

DinoMyte
DinoMyte

Reputation: 8858

You can get the key-value pair by iterating through each element in array imgs using $.each

var imgs = {
    1111: "my/image/path1",
    2111: "my/image/path2",
    1211: "my/image/path3",
    1311: "my/image/path4"
}


$.each(imgs,function(key,value)
{
    if(key === 1111)
     return value; // This would give you the path "my/image/path1"

});

Upvotes: -1

Related Questions