I am using ajax to get a small set of data back from the server which returns JSON data with the following format:
{
"data": [
{
"id": "1",
"value": "One"
},
{
"id": "2",
"value": "Two"
},
{
"id": "3",
"value": "Three"
}
]
}
On the client side, this is assigned to a variable named response
. I use response.data
to get the contents.
The question is, is there an easier way to get the value without doing a loop?
I'm kinda looking for something like this response[id==2].value
which should give me "Two".
I'm open for any suggestions if this is not possible.
I am using ajax to get a small set of data back from the server which returns JSON data with the following format:
{
"data": [
{
"id": "1",
"value": "One"
},
{
"id": "2",
"value": "Two"
},
{
"id": "3",
"value": "Three"
}
]
}
On the client side, this is assigned to a variable named response
. I use response.data
to get the contents.
The question is, is there an easier way to get the value without doing a loop?
I'm kinda looking for something like this response[id==2].value
which should give me "Two".
I'm open for any suggestions if this is not possible.
Share Improve this question edited Aug 19, 2013 at 5:06 Mr_Green 41.8k47 gold badges170 silver badges276 bronze badges asked Aug 19, 2013 at 5:03 RavenXVRavenXV 3771 gold badge5 silver badges15 bronze badges 3- duplicate? stackoverflow./questions/8481380/… – Oleg Mikheev Commented Aug 19, 2013 at 5:05
-
1
I understand your question but in your case this can be done..
response.data[2-1].value
– Mr_Green Commented Aug 19, 2013 at 5:09 - http://jsfiddle/uHbZt/8/ This? – user2587132 Commented Aug 19, 2013 at 5:17
2 Answers
Reset to default 7You could take a functional approach and use the Array.filter method:
var matchingResults = JSON['data'].filter(function(x){ return x.id == 2; });
// procede to use matching elements...
If you parse it into a javascript object using something like jQuery's json parse method, you could just reference the various items in the array like a normal javascript array.
Do it like this:
var dataArray = $.parseJSON(myJson).data;
var theFirstData = dataArray[0]; //get the data with id "1"
Alternately, if you don't want to use jQuery, you can use JSON.parse(jsonToParse)
. Here're the docs for that method.