Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: If key exists in array, get value

I am trying to see if a certain key exists in an array, and if so, return it's value:

if(jQuery.inArray(live_ids.grade, item.SizePrice) !== -1) {

    console.log(item.SizePrice);

}

This will return:

{"8":"15.00","7":"20.00","1":"6.00","6":"11.00","2":"7.00","3":"8.00","4":"9.00","5":"10.00","11":"20.00","9":"10.00","10":"15.00","13":""}

Now, live_ids.grade = 9, so I want to be able to return 10.00... how do I do that?

like image 514
MultiDev Avatar asked Feb 22 '16 04:02

MultiDev


People also ask

How do you check if a value exists in an array in jQuery?

1) Using jQuery If you are someone strongly committed to using the jQuery library, you can use the . inArray( ) method. If the function finds the value, it returns the index position of the value and -1 if it doesn't.

How do you check if an array of objects contains a key?

Using the Object. key generates and returns an array whose components are strings of the names (keys) of an object's properties. This may be used to loop through the object's keys, which we can then use to verify if any match a certain key in the object.

How do you check if an array has a key in jQuery?

“jquery check if array key exist” Code Answer's obj["key"] !== undefined // false, but the key exists!

How do you check if a key exists in an array JavaScript?

For checking if an object exists in an array, we need to use the indexOf method on the array. If the object is not found, -1 is returned, else its index is returned.


Video Answer


1 Answers

Here you check if the number is in the obj than execute else show error.

var obj = {
    "8":"15.00",
    "7":"20.00",
    "1":"6.00",
    "6":"11.00",
    "2":"7.00",
    "3":"8.00",
    "4":"9.00",
    "5":"10.00",
    "11":"20.00",
    "9":"10.00",
    "10":"15.00",
    "13":""
};

var number = 9;

if(number in obj){
    alert(obj[number])
} else {
    alert("This number does not exists")
}
like image 60
Hakan Kose Avatar answered Sep 25 '22 20:09

Hakan Kose