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;
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 .
var i=0;
while(i<jarray.length) {
if(jarray[i].id==id) {
var val=jarray[i].value;
break;
}
}
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
like this:
for (i=0;i<jarray.length;i++)
{
var tempValue = jarray[i];
if (tempValue["id"] == id)
alert( "value is : " + tempValue["value"] );
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.