使用javascript从JSON获取特定值

时间:2021-07-20 21:14:28

I am using ajax to get a small set of data back from the server which returns JSON data with the following format:

我使用ajax从服务器返回一小组数据,返回JSON数据,格式如下:

{
    "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.

在客户端,这被分配给名为response的变量。我使用response.data来获取内容。

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".

问题是,有没有更简单的方法来获得价值而不进行循环?我有点像这个回复[id == 2] .value,它应该给我“两个”。

I'm open for any suggestions if this is not possible.

如果不可能,我愿意接受任何建议。

2 个解决方案

#1


3  

You could take a functional approach and use the Array.filter method:

您可以采用函数方法并使用Array.filter方法:

var matchingResults = JSON['data'].filter(function(x){ return x.id == 2; });
// procede to use matching elements...

#2


2  

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.

如果使用jQuery的json parse方法将其解析为javascript对象,则可以像普通的javascript数组一样引用数组中的各个项。

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.

或者,如果您不想使用jQuery,则可以使用JSON.parse(jsonToParse)。这是该方法的文档。

#1


3  

You could take a functional approach and use the Array.filter method:

您可以采用函数方法并使用Array.filter方法:

var matchingResults = JSON['data'].filter(function(x){ return x.id == 2; });
// procede to use matching elements...

#2


2  

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.

如果使用jQuery的json parse方法将其解析为javascript对象,则可以像普通的javascript数组一样引用数组中的各个项。

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.

或者,如果您不想使用jQuery,则可以使用JSON.parse(jsonToParse)。这是该方法的文档。