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;
Naftali
  • 144,921
  • 39
  • 244
  • 303
User
  • 1,644
  • 10
  • 40
  • 64

4 Answers4

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.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 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'` – jackwanders Jul 12 '12 at 13:18
  • 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 – jackwanders Jul 12 '12 at 13:40
0
var i=0;
while(i<jarray.length) {
  if(jarray[i].id==id) {
    var val=jarray[i].value;
    break;
  }
}
Cecchi
  • 1,525
  • 9
  • 9
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
Cecchi
  • 1,525
  • 9
  • 9
0

like this:

for (i=0;i<jarray.length;i++)
    {
        var tempValue = jarray[i];
        if (tempValue["id"] == id)
            alert( "value is : " + tempValue["value"] );
    }
Al-Mothafar
  • 7,949
  • 7
  • 68
  • 102