Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a JSON Object, How to find a item based on a Key?

Given a JSON object like:

var data = {items: [
{value: "21", name: "Mick Jagger"},
{value: "43", name: "Johnny Storm"},
{value: "46", name: "Richard Hatch"},
{value: "54", name: "Kelly Slater"},
{value: "55", name: "Rudy Hamilton"},
{value: "79", name: "Michael Jordan"}
]};

How can I do something like this:

datagood = data.where(value == 55)

Is something like that possible with JS/jQuery? Thanks

like image 537
AnApprentice Avatar asked Nov 30 '22 04:11

AnApprentice


2 Answers

jQuery's grep function lets you filter through an array:

var datagood = $.grep(data.items, function (item) {
    return item.value == 55;
});

If you want more powerful utilities, take a look at this SO question on JS LINQ libraries.

Alternatively, underscore.js is also useful for array/object manipulation.

like image 103
David Tang Avatar answered Dec 09 '22 16:12

David Tang


jLinq? http://www.hugoware.net/Projects/jLinq

like image 24
Jonathan Avatar answered Dec 09 '22 17:12

Jonathan