【发布时间】:2018-02-09 23:45:00
【问题描述】:
我有一个葡萄酒数组,其中包含带有每种葡萄酒数据的对象:
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 中有更好的方法,那么我会全力以赴!
【问题讨论】:
-
是否应该为每个属性搜索一个值?或者您是否为每个属性指定了不同的搜索值?
-
也许我误解了你的问题,但我认为简单地使用 OR 运算符就可以了?您可以通过创建函数
(wine.wineName.toLowerCase().indexOf(search.toLowerCase())>=0来清理这部分。或者,您可以使用正则表达式。 -
顺便说一句,从人们最终发布的任何过滤方法中进行选择,但 computed property 将是在 Vue 中使用它的理想方式。
-
@Bert 我将其填充到计算属性中并返回结果 :) 感谢您向其他人说明这一点!
标签: javascript arrays vue.js filtering vuejs2