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?
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?
- use .each() or api.jquery.com/jquery.map – Confused Commented Feb 22, 2016 at 4:20
- item.SizePrice[live_ids.grade] will return value at that index – Abdul Basit Commented Feb 22, 2016 at 4:26
3 Answers
Reset to default 15Here 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")
}
here is your solution...
<script type="text/javascript">
var a={"k1": 100, "k2": 200, "k3": 300};
var ky=prompt("enter key :");
for (var k in a){
if (a.hasOwnProperty(k)) {
if(k==ky){
alert("Key is " + k + ", value is" + a[k]);
}
}
}
</script>
item.SizePrice
appears to be an Object
, not an Array
. You can use for..in
loop on the object , break
the loop after console.log()
called
var items = {
"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": ""
},
n = 9;
for (var prop in items) {
if (items[n]) {
console.log(items[n]);
break;
}
}