我有一系列的葡萄酒,其中包含带有每种葡萄酒数据的对象:
var wines = [
{ _id: '59a740b8aa06e549918b1fda',
wineryName: 'Some Winery',
wineName: 'Pinot Noir',
wineColor: 'Red',
imageLink: '/img/FortBerensPN.png' },
{ _id: '59a7410aaa06e549918b1fdb',
wineryName: 'Some Winery',
wineName: 'Pinot Gris',
wineColor: 'White',
imageLink: '/img/FortBerensPG.png' },
{ _id: '59a74125aa06e549918b1fdc',
wineryName: 'Some Winery',
wineName: 'Rose',
wineColor: 'Rose',
imageLink: '/img/FortBerensRose.png' },
{ _id: '59a74159aa06e549918b1fdd',
wineryName: 'Some other Winery',
wineName: 'Rose',
wineColor: 'Rose',
imageLink: '/img/FortBerensRose.png' },
{ _id: '59a7417aaa06e549918b1fde',
wineryName: 'Some other Winery',
wineName: 'Pinot Gris',
wineColor: 'White',
imageLink: '/img/FortBerensPG.png' },
{ _id: '59a8721f4fd43b676a1f5f0d',
wineryName: 'Some other Winery',
wineName: 'Pinot Gris',
wineColor: 'White',
imageLink: '/img/FortBerensPG.png' },
{ _id: '59a872244fd43b676a1f5f0e',
wineryName: 'Winery 3',
wineName: 'Pinot Noir',
wineColor: 'Red',
imageLink: '/img/FortBerensPN.png' } ]
我可以弄清楚如何搜索(不区分大小写)酒对象,同时指定要搜索对象的键,如下所示:
var search = 'Noir'
filteredWines = function () {
return wines.filter(function(wine){
return (wine.wineName.toLowerCase().indexOf(search.toLowerCase())>=0;
});
};
返回值:
[ { _id: '59a740b8aa06e549918b1fda',
wineryName: 'Some Winery',
wineName: 'Pinot Noir',
wineColor: 'Red',
imageLink: '/img/FortBerensPN.png' },
{ _id: '59a872244fd43b676a1f5f0e',
wineryName: 'Winery 3',
wineName: 'Pinot Noir',
wineColor: 'Red',
imageLink: '/img/FortBerensPN.png' } ]
然而,如果var search = 'Winery 3'
还是var search = 'red'
那么它显然会返回任何结果,因为它是在寻找的价值wineName
阵列中的每个对象。
那么,有没有一种方法可以使用过滤器(或另一种方法?)搜索所有键值,甚至更好地搜索多个指定键值并返回匹配对象的数组?
就像是:
filteredWines = function () {
return wines.filter(function(wine){
return ((wine.wineName.toLowerCase() && wine.wineName.toLowerCase()
&& wine.wineName.toLowerCase()).indexOf(search.toLowerCase())>=0;
});
};
还是我完全把错误的树种了?
PS。我正在使用Vue.js 2,因此,如果在vue中有更好的方法,那么我会不胜枚举!
您可能有一个更通用的函数,它将扫描字符串的所有属性。匹配时循环遍历所有属性值,Object.values()
并用于some
在遇到匹配项后立即纾困:
filteredWines = function (search) {
var lowSearch = search.toLowerCase();
return wines.filter(function(wine){
return Object.values(wine).some( val =>
String(val).toLowerCase().includes(lowSearch)
);
});
}
如果您希望通过特定的关键字来搜索:
filteredWines = function (search, keys) {
var lowSearch = search.toLowerCase();
return wines.filter(function(wine){
return keys.some( key =>
String(wine[key]).toLowerCase().includes(lowSearch)
);
});
}
称为
filteredWines('Winery 3', ['wineryName', 'wineName']);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句