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?
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.
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.
“jquery check if array key exist” Code Answer's obj["key"] !== undefined // false, but the key exists!
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.
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With