문제

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]
도움이 되었습니까?

해결책

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

다른 팁

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).

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.

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;
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top