我必须根据一些偏好来过滤对象数组。
我需要过滤的数组如下:
const products = [
{value: 'v1', color: 'blue'},
{value: 'v1', color: 'black'},
{value: 'v1', color: 'red'},
{value: 'v2', color: 'green'},
{value: 'v2', color: 'red'},
{value: 'v3', color: 'red'},
{value: 'v4', color: 'blue'}
]
首选项如下:
const preferences = [
{type: {value: 'v1', label: 'l1'}, color: 'blue'},
{type: {value: 'v1', label: 'l1'}, color: 'red'},
{type: {value: 'v2', label: 'l2'}, color: 'blue'},
{type: {value: 'v3', label: 'l3'}, color: 'red'},
{type: {value: 'v4', label: 'l4'}, color: 'green'}
]
过滤器应返回所有与首选项的值和颜色均匹配的对象。 因此理想的结果应该是:
[
{value: 'v1', color: 'blue'},
{value: 'v1', color: 'red'},
{value: 'v3', color: 'red'},
]
我尝试从发现here的示例中使用以下功能:
function filterArray(allObjects, preferenceFilter) {
const filterKeys = Object.keys(preferenceFilter);
return allObjects.filter(item => {
return filterKeys.every(key => {
if (typeof preferenceFilter[key] !== 'function') return true;
return preferenceFilter[key](item[key]);
});
});
}
问题是我需要将首选项转换为以下形式的过滤条件:
{color: x => x === 'red', type: y => y === 'v1' || y === 'v3'},
{color: x => x === 'blue', type: y => y === 'v1' || y === 'v2'},
{color: x => x === 'green', type: y => y === 'v4'}
我该怎么做?还是有解决这个问题的更好方法。
在此先感谢您的帮助!
答案 0 :(得分:2)
您可以filter种产品,以便如果首选项具有some个匹配项,则选择该产品。
const products = [
{value: 'v1', color: 'blue'},
{value: 'v1', color: 'black'},
{value: 'v1', color: 'red'},
{value: 'v2', color: 'green'},
{value: 'v2', color: 'red'},
{value: 'v3', color: 'red'},
{value: 'v4', color: 'blue'}
];
const preferences = [
{type: {value: 'v1', label: 'l1'}, color: 'blue'},
{type: {value: 'v1', label: 'l1'}, color: 'red'},
{type: {value: 'v2', label: 'l2'}, color: 'blue'},
{type: {value: 'v3', label: 'l3'}, color: 'red'},
{type: {value: 'v4', label: 'l4'}, color: 'green'}
];
const filtered = products.filter(a => preferences.some(b => b.type.value === a.value && b.color === a.color));
console.log(filtered);
答案 1 :(得分:2)
尝试一下,我已经根据您的用例进行了测试。一切正常。
var final = [];
for(let i=0 ; i<products.length; i++){
preferences.map((data)=>{
if(data.color === products[i].color && data.type.value === products[i].value){
final.push(data);
}
})
}
console.log(final)