如何过滤JavaScript对象以仅显示我需要的数据

时间:2011-12-12 21:40:26

标签: javascript jquery json underscore.js

我有这个json对象 - 它的缩写,但它看起来有点像下面的

{
"q": [
    {
        "a": [],
        "asked_at": "2011-12-08T05:58:45.695958",
        "closed_at": null,
        "event": "/api/v1/event/2/",
        "id": "2",
        "is_open": true,
        "is_public": true,
        "question": "Testing the question entry point with curl",
        "updated_at": "2011-12-08T05:58:47.026834",
        "user": {
            "email": "test@t.com",
            "first_name": "",
            "last_name": "",
            "profile": [],
            "username": "wout"
        }
    },
    {
        "a": [],
        "asked_at": "2011-12-08T05:59:39.941603",
        "closed_at": null,
        "event": "/api/v1/event/2/",
        "id": "3",
        "is_open": true,
        "is_public": true,
        "question": "Testing another question entry point with curl",
        "updated_at": "2011-12-08T05:59:43.388709",
        "user": {
            "email": "test@t.com",
            "first_name": "",
            "last_name": "",
            "profile": [],
            "username": "wout"
        }
    }   
]
}

其中q是被问到的问题,并且每个答案都是答案(未显示,在此示例中没有给出答案)。 如果我只想获得一个id为'3'的项目,那么我将如何处理它,以便我得到以下结果:

{
        "a": [],
        "asked_at": "2011-12-08T05:59:39.941603",
        "closed_at": null,
        "event": "/api/v1/event/2/",
        "id": "3",
        "is_open": true,
        "is_public": true,
        "question": "Here's a test entry point with curl",
        "updated_at": "2011-12-08T05:59:43.388709",
        "user": {
            "email": "test@t.com",
            "first_name": "",
            "last_name": "",
            "profile": [],
            "username": "wout"
        }
    }

希望有人可以提供帮助 - 非常感谢! 马可

2 个答案:

答案 0 :(得分:4)

grep函数可以过滤数组

var questionsWithId3 = $.grep(yourObj.q, function() { return this.id === "3"; });

这将返回一个数组,所以如果你确定只有一个结果,你可以这样做:

var questionWithId3 = $.grep(yourObj.q, function() { return this.id === "3"; })[0];

答案 1 :(得分:3)

假设您的JSON已解析为JavaScript,这是一个本机JavaScript解决方案:

var obj = {
    q: [
       // ...
    ]
};

var result;

for( var i = 0; i < obj.q.length; ++i ) {
    if( obj.q[i] && obj.q[i].id === '3' ) {
        result = obj.q[i];
        break;
    }
}