Reputation: 79
I am working to filter a large json data set, I'd like to know how can I select json objects vertically.
Lat's take this small example, I'd like to select all the books with the name of author contains 'Evelyn'
data= [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price":8
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 8
},
{ "category": "fiction",
"author": "Evelyn Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
as a result I should get:
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 8
},
{ "category": "fiction",
"author": "Evelyn Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
Can I do it this way:
$.each(data,function(i,el)
{
var newdata;
if (data.author.contains('Evelyn')) newdata.push()
});
Another way :
data.where( "( n, i ) => n.author.contains('Evelyn') " ) ;
Do you have where is the problem in the both ways, what is the fastest ways to tackle this problem as I have a huge dataset ?
Upvotes: 0
Views: 2821
Reputation: 122906
You can use Array.filter
:
var filtered = data.filter(function(a){return +(a.price) >= 8;}
Or filter on the author
field:
var filtered = data.filter(function(a){return /evelyn/i.test(a.author);});
// now [filtered] contains the objects from [data]
// where 'author' contains 'Evelyn'
// filtered.length => 2
// filtered[0].category => 'fiction'
MDN filter documentation (including a shim for older browsers)
Upvotes: 4
Reputation: 951
contains
operator will not work here, you'll have to use the indexOf function here.
The below code should work fine
data= [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price":8
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 8
},
{ "category": "fiction",
"author": "Evelyn Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}];
data.forEach(function(args){
if(args.author.indexOf('Evelyn') >= 0){
console.log(args);
}
});
Upvotes: 0
Reputation: 94101
You can use filter
:
data.filter(function(book) {
return /Evelyn/.test(book.author);
});
Upvotes: 0
Reputation: 7429
Have you tried this? I've used it in some of my projects and really can recommend it. http://www.hugoware.net/projects/jlinq
Upvotes: 0