0

I Create the JSON Array like in the name of jarray.

It has id and the corresponding value.

And I have an another variable arr.

Now, how do I get the value of the value from json array using id.

It means if i need to check the jarray by using the var id=04.

If i found 04 i need the value of the particular id like Apple as a out put.

How to use the If condition in Json array?

var jarray=[{"id":"04","value":"Apple"},{"id":"13","value":"orange"}];
var id=04;
2
  • possible duplicate of JSON find in JavaScript Commented Jul 12, 2012 at 13:14
  • What are you trying to achieve? Commented Jul 12, 2012 at 13:14

4 Answers 4

1

This returns an array of all the items whose id is "04" :

var matches = jarray.filter(function(a){return a.id==id;});

If you're sure there is only one, you can take matches[0];.

Note that this works with id provided as "04" or 04.

To ensure compatibility with old browsers (which might not have the filter function) see this.

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

2 Comments

in practice, he'd want to check a.id === id. @user, note though that your id variable is not a string, but a number, you'd need to change it to var id = '04'
yes, but it's not a best practice to rely on the "flexibility" of the == operator. it's better to use '===' and to ensure your values are of the same type
0

like this:

for (i=0;i<jarray.length;i++)
    {
        var tempValue = jarray[i];
        if (tempValue["id"] == id)
            alert( "value is : " + tempValue["value"] );
    }

Comments

0
var i=0;
while(i<jarray.length) {
  if(jarray[i].id==id) {
    var val=jarray[i].value;
    break;
  }
}

Comments

0

You can either use something like Underscore's _.find` method, or write your own which might be more specific to your case:

function findId(id, arr, member) {
  for(i in arr) {
    // You could use === here depending on your needs
    if(arr[i]['id'] == id) {
      return member === undefined ? arr[i] : arr[i][member];
    }
  }
  return false;
}
findId('04', jarray, 'value'); // Apple

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.