我有一个包含对象与每个数据葡萄酒的葡萄酒的数组:如何使用过滤器来搜索数组中对象的多个键值?
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'
那么它将obviousl y不返回结果,因为它正在查看数组中每个对象的值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内部有更好的方法,那么我就是耳朵!
应该为每个属性搜索一个值吗?或者你是否为每个属性指定了不同的搜索值? – Bert
也许我误解了你的问题,但我认为只是使用OR运算符会起作用吗?你可以通过创建一个函数'(wine.wineName.toLowerCase()。indexOf(search.toLowerCase())> = 0'来清理这部分。或者,你可以使用正则表达式。 – Sia
顺便说一句,方法人最终张贴,但[计算属性](https://vuejs.org/v2/guide/computed.html)将是在Vue中使用它的理想方式。 – Bert