Reputation: 34969
Consider a JSON like this:
[{
"type": "person",
"name": "Mike",
"age": "29"
},
{
"type": "person",
"name": "Afshin",
"age": "21"
},
{
"type": "something_else",
"where": "NY"
}]
I want to search in the JSON value with a key (for example type='person'
) and then select a whole object of matched item in JSON. For example when I search for type='person'
I expect this value:
[{
"type": "person",
"name": "Mike",
"age": "29"
},
{
"type": "person",
"name": "Afshin",
"age": "21"
}]
Because it's a really big JSON value, I don't want to do a brute-force search in all nodes, so I think the only way is using Regular Expressions but I don't know how can I write a Regex to match something like above.
I'm using NodeJs for the application.
Upvotes: 0
Views: 172
Reputation: 7117
Plain javascript :
var results = dataset.filter(function(p) {
if(p.type == 'person')
return true;
});
Upvotes: 1
Reputation: 4561
If the requirement is to scan multiple times through the collection, the following one time construction overhead might be of worth.
Use hashing based on values of type.Convert the current data structure to hash map.
var hashMap ={
};
hashMap['person'] =[{},{}];
Hope this helps you.
Upvotes: 0
Reputation: 743
Use
$.grep(jsonarrayobj,function(n, i){
if(n.type==="person")
{}
})
Upvotes: -2
Reputation: 22797
Using underscore.js#where:
var results = _(yourObject).where({ type: 'person' })
If your data set is very very big [e.g. 10k or so], consider filtering / paginating stuff server side.
Upvotes: 2