![](/img/trans.png)
[英]Javascript Filter an array based on multiple conditions using native functions
[英]How to chain multiple filter functions in javascript with multiple conditions array
我有一个包含多个属性的数据数组,需要通过选择框将其过滤掉。 就像电子商务网站一样,您可以在其中选择类别,然后选择特定大小,价格,颜色等。 所有过滤器组合在一起,得出结果。
如何筛选多个属性并最终返回仅包含所选值的数据? http://jsfiddle.net/Jeffwise/z2y41k85/3/
var vm = new Vue({
el: '#root',
data: {
list: [{
name: 'asd',
category: 1
},
{
name: 'zxc',
category: 1
},
{
name: 'qwe',
category: 1
},
{
name: 'qqq',
category: 2
},
{
name: 'www',
category: 2
},
{
name: 'eee',
category: 2
},
{
name: 'rrr',
category: 2
},
{
name: 'ttt',
category: 2
},
{
name: 'ert',
category: 1
},
{
name: 'wer',
category: 2
},
{
name: 'sdf',
category: 1
},
{
name: 'dfg',
category: 2
},
{
name: 'xcv',
category: 1
}
],
categories: [{
id: 1,
name: 'cat 1'
},
{
id: 2,
name: 'cat 2'
}
],
keyword: 'e',
category: 1
},
computed: {
filteredByAll() {
return getByCategory(getByKeyword(this.list, this.keyword), this.category)
},
filteredByKeyword() {
return getByKeyword(this.list, this.keyword)
},
filteredByCategory() {
return getByCategory(this.list, this.category)
}
}
});
function getByKeyword(list, keyword) {
const search = keyword.trim()
if (!search.length) return list
return list.filter(item => item.name.indexOf(search) > -1)
}
function getByCategory(list, category) {
if (!category) return list
return list.filter(item => item.category === category)
}
我认为我正在寻找的是将多个过滤功能链接在一起。 但是,你是怎么做的? 这个js小提琴非常接近,但是如何为它添加更多过滤器,以便可以检查更多的功能/过滤器? 我总共有10个过滤器,应该一起“工作”。 我是一个绝对的初学者,还在学习。
当然,有几种方法可以解决此问题。
与其链接(例如, data.withKey('cheap').withBrand('Levis')
-需要一个带有可链接方法的新类),我将采用一种采用一个filterObject的递归方法。 每个key: value
对都是一个过滤器:
methods: {
filter(data, filters) {
// filters should be an object of filterOptions, e.g. { name: 'blue', weight: 20 }
const filterProp = Object.keys(filters)[0]; // get first prop to filter for
// filter your data by this prop and the corresponding value
const filteredData = data.filter((entry) => {
return entry[filterProp] === filters[filterProp]
});
// get all the other filters through dynamic destructuring
const { [filterProp]: deletedFilter, ...otherFilters } = filters;
// if there are no other filters return filteredData,
// else filter filteredData again with the remaining filters
return Object.keys(otherFilters).length <= 0
? filteredData : this.filter(filteredData, otherFilters);
},
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.