使用javascript从JSON获取特定值 [英] Getting specific value from JSON using javascript

查看:64
本文介绍了使用javascript从JSON获取特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"
        }
    ]
}

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

On the client side, this is assigned to a variable named response. I use response.data to get the contents.

问题是,是否有更简单的方法来获取没有循环的价值?
我有点像这样的回复[id == 2] .value 这应该给我两个。

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.

推荐答案

你可以拿一个功能方法并使用 Array.filter 方法:

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

这篇关于使用javascript从JSON获取特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆