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

如何过滤JavaScript对象以仅显示所需的数据,javascript,jquery,json,underscore.js,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,

我有一个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是一个被问的问题,每个a都是一个答案(未显示,本例中未给出答案)。 如果我只想得到一个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"
        }
    }
希望有人能帮忙-非常感谢! Marco

该函数可以过滤数组

var questionsWithId3 = $.grep(yourObj.q, function() { return this.id === "3"; });
这将返回一个数组,因此如果您确定只有一个结果,则可以执行以下操作:

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

假设您的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;
    }
}
var obj={
问:[
// ...
]
};
var结果;
对于(变量i=0;i
只要您将其更改为
this.id==“3”
,我将+1您,因为该数字存储为字符串。:)看看。只是一个迂腐的观点——正如人们在过去教我的那样,没有JSON对象这样的东西。如果它是字符串,那么它是json,如果它是对象,那么它就是对象。亚当,谢谢-这是一个值得记住的好东西。你喜欢预增量运算符++i,不是吗:)我想你肯定不会有可怕的副作用+1.btw@AdamRackis:谢谢。是的,这两种方式在这里都很安全,但除此之外,我更愿意抓住长度,然后做
while(len--){…
,除非有令人信服的理由从一开始就开始。
while(len--)
-我喜欢“整洁”像这样的代码依赖于语言的细微差别——0是错误的,并且——在循环检查之后发生。那么人们会像对待我一样对你这样的东西大骂吗?也就是说,我让人们认为
return\u-foo???(\u-foo=getFoo())
不够清晰。(在C中)Pff+1。我喜欢
for(变量i=0,len=obj.q.长度;i@AdamRackis:是的,人们可能会对其中的一些事情感到紧张。我想一旦你理解了这种语言,它们就会像其他任何东西一样清晰。我声明多个变量的方式可能会让一些人发疯。