FlavorScape
FlavorScape

Reputation: 14309

Select json object based on key value pair

This might be a noob question, but I'm wondering if there's a way to select a json object without having to loop through key value pairs. I've done similar things with e4x, but I'm not sure how to do it syntactically for js. For example

 var data =   { "objects":[
                {"foo":"x","bar":"a"},
                {"foo":"y","bar":"b"}
              ]}

So instead of a for loop, some way to declare

 var someObject = data.objects[where objects.foo == x]

Upvotes: 2

Views: 8571

Answers (4)

Silvio Delgado
Silvio Delgado

Reputation: 6975

The question is old, but may this answer can help someone.

To select an item from list, you can use Javascript filter function:

var data = { "objects":[
                   {"foo":"x","bar":"a"},
                   {"foo":"y","bar":"b"}
                ]}

var someobject = filterObject('x');

function filterObject(fooValue) {
    return data.objects.filter(function(item) {
        return item.foo == fooValue;
    }
}

Upvotes: 0

Linh Dam
Linh Dam

Reputation: 2219

I was searching and just found this: https://github.com/lloyd/JSONSelect. I haven't tried it yet but it seems to be a good choice.

Upvotes: 0

FlavorScape
FlavorScape

Reputation: 14309

This question was asked two years ago before jsonQ. jsonQ allows us to write code to find siblings, traverse trees etc. without having to write a bunch of loops inside loops. While the question wanted a way to find it in native JS, I think my 2-year-old question is a bit naive now. I was really looking for a library like jsonQ to avoid writing a bunch of ugly loops (though I could do the work myself).

Upvotes: 0

kirilloid
kirilloid

Reputation: 14304

You may do that w/o manually iterate over data, but some code should iterate over object anyway (so doesn't expect lightning speed on rather large objects).

There's a library for that: jsonpath

Upvotes: 3

Related Questions