我有一些以JSON格式存储的数据需要进行搜索。有不同的标签可用,当我点击它们时,它会在JSON中搜索并返回具有这些标签的项目。为此,我使用了一个js函数。它在第一次执行时可以正确地工作,但是当我在函数中添加第二个过滤器时,它会返回错误的数据。
可用的过滤器如下:
装帧方式
- 平装
- 精装
- 有声读物
- 组合套装
类别
- 经典摇滚
- 流行
- 流行摇滚
- 电子流行
- 轻柔摇滚
- 摇滚
语言
- 德语
- 英语
- 法语
作者
- 男性
- 女性
- 男/女
这里是我正在使用的JSON和代码:
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'))
category = rock
时,它返回 Book 4, Book 5 和 Book 6
,但如果我同时推送 category = rock
和 language = french
,则应该仅返回 Book 5
,但它并未返回正确的结果。请问有谁能帮忙解决?
category = rock
和language = french
,返回的结果应该只有Book 5
,但它没有返回正确的结果。 - hashtagerrors'rock'
或者'electro pop,rock,classic rock'
或者'soft rock'
中搜索'rock'
。 - Nina Scholz