>我有两个数组数据
checked: [
'orange', 'apple', 'juice'
]
和第二
products: [
'0': {
title: 'this is product title',
categories: [
'apple', 'juice'
]
}
]
我想使用复选框使用计算属性过滤数据
我试过这个
computed: {
filterProducts(){
return this.products.filter(product => this.checked.includes(product.categories));
}
}
但它不起作用,我该怎么做
你可以使用.every()
。
下面是一个示例:
checked = [
'orange', 'apple', 'juice'
]
products = [{
title: 'this is product title',
categories: [
'apple', 'juice'
]
}];
const filteredProducts = products.filter(({ categories }) => categories.every(cat => checked.includes(cat)));
console.log(filteredProducts);
这将返回一个产品数组,这些产品具有一个categories
数组,其所有值都包含在checked
数组中。
我不确定这是否正是您要做的,如果您想使用categories
数组获取所有产品,该数组在checked
数组中至少有一个值,请使用.some()
而不是.every()
.
您正在尝试检查字符串数组是否包含数组(即使您的初始数组包含数组,该数组也不起作用(。不使用.includes()
,在product.categories
上使用.every()
来检查此数组中的所有项目是否都包含在选中:
const checked = ['orange', 'apple', 'juice'];
const products = [
{
title: 'this is product title',
categories: ['apple', 'juice']
}
];
const computed = products.filter(product => product.categories.every(item => checked.includes(item) || !checked.length));
console.log(computed);