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]
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]
Share
edited Mar 6, 2012 at 20:18
FlavorScape
asked Mar 6, 2012 at 19:25
FlavorScapeFlavorScape
14.4k12 gold badges79 silver badges123 bronze badges
2
- That's not JSON, that's object literal notation. – Matthew Commented Mar 6, 2012 at 19:32
- You are incorrect. JSON is a subset of Object Literal notation, and in fact requires identifiers in value pairs to be strings only. – FlavorScape Commented Mar 6, 2012 at 20:22
4 Answers
Reset to default 3You 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./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;
}
}