8

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?

2
  • use .each() or api.jquery.com/jquery.map Commented Feb 22, 2016 at 4:20
  • item.SizePrice[live_ids.grade] will return value at that index Commented Feb 22, 2016 at 4:26

3 Answers 3

15

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")
}

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

Comments

1

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>

Comments

0

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;
  }
}

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.