Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting specific value from JSON using javascript

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.

like image 824
RavenXV Avatar asked Aug 19 '13 05:08

RavenXV


1 Answers

You 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...
like image 172
dwerner Avatar answered Oct 06 '22 01:10

dwerner