Marco
Marco

Reputation: 2463

How to filter a JavaScript object to show only the data I need

I have this json object- it's abbreviated, but it looks somewhat like the following

{
"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": "[email protected]",
            "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": "[email protected]",
            "first_name": "",
            "last_name": "",
            "profile": [],
            "username": "wout"
        }
    }   
]
}

Where q is a question being asked, and every a would be an answer (not shown, no answers are given in this example). How would I go about it, if I wanted to get only the one item with an id of '3' so that I would be left with a result of:

{
        "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": "[email protected]",
            "first_name": "",
            "last_name": "",
            "profile": [],
            "username": "wout"
        }
    }

Hope someone can help- Thanks alot! Marco

Upvotes: 3

Views: 886

Answers (2)

RightSaidFred
RightSaidFred

Reputation: 11327

Assuming your JSON is parsed into JavaScript, here's a native JavaScript solution:

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;
    }
}

Upvotes: 3

Adam Rackis
Adam Rackis

Reputation: 83366

The grep function can filter an array

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

This will return an array, so if you're sure there will only be one result, you can do:

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

Upvotes: 4

Related Questions