I have data in JSON format in which I need to perform search. There are different tags available and when I click on them it searches in JSON and returns the items which has those tags. For this I am using a js function. It works correctly for the first time but When I push second filter in the function it returns wrong data.
Available Filters are:
Binding
- Paperback
- Hardcover
- Audiobook
- Boxed Set
Category
- Classic Rock
- Pop
- Pop Rock
- Electro Pop
- Soft Rock
- Rock
Language
- German
- English
- French
Author
- Male
- Female
- Male/Female
Here is the JSON and code I am using:
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 key
function getFilteredElement(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 array
var keyArray = item[key].split(',');
// now checking if the passed value has a presence in the above array
if (keyArray.indexOf(value) !== -1) {
// if present pushed the book name
bookFilter.push(item.title);
}
});
// returning the array of books
return bookFilter;
}
console.log(getFilteredElement('category', 'rock'))
For e.g. When I push category = rock it returns Book 4, Book 5 and Book 6 but If I push category = rock and language = french, the returned result should only be Book 5 but it doesn't return correct results.
Could anyone please help.
category = rockandlanguage = french, the returned result should only beBook 5but it doesn't return correct results.