Searching A Json With Javascript With Exact Tags
I have a following JSON where search is to be performed by selecting filters: { 'Books': [ { 'title': 'Book 1', 'binding': 'paperback', 'category': '
Solution 1:
Use forEach
to iterate the array and use indexOf
to find if the required value is present in that key
var m = {
"Books": [{
"title": "Book 1",
"binding": "paperback",
"category": "pop",
"language": "english",
"author": "male"
},
{
"title": "Book 2",
"binding": "hardcover",
"category": "pop rock,electro pop",
"language": "french",
"author": "female"
},
{
"title": "Book 3",
"binding": "audiobook",
"category": "soft rock",
"language": "german",
"author": "male,female"
},
{
"title": "Book 4",
"binding": "boxed set",
"category": "rock,classic rock",
"language": "english",
"author": "female,male"
},
{
"title": "Book 5",
"binding": "paperback",
"category": "electro pop,rock,classic rock",
"language": "french",
"author": "male/female"
},
{
"title": "Book 6",
"binding": "paperback",
"category": "rock",
"language": "french",
"author": "male"
}
]
}
// a function which accepts key which is one of binding,category,language,author.// the array will be filtered on this keyfunctiongetFilteredElement(key, value) {
var bookFilter = [];
m.Books.forEach(function(item){
var getFilterField = item[key];
// since the value is a string, so splitting it and creating an arrayvar keyArray = item[key].split(',');
// now checking if the passed value has a presence in the above arrayif (keyArray.indexOf(value) !== -1) {
// if present pushed the book name
bookFilter.push(item.title);
}
});
// returning the array of booksreturn bookFilter;
}
console.log(getFilteredElement('category', 'rock'))
Post a Comment for "Searching A Json With Javascript With Exact Tags"