如何在对象数组上实现通配符过滤器?即使筛选器仅从一开始就起作用,也应该没问题。应该能够过滤对象的所有属性。
应该以与lodash过滤器相同的方式工作,除了通配符过滤器也可以工作。谢谢。
const sampleProducts = [{
color: 'red',
value: '#f00',
},
{
color: 'green',
value: '#0f0',
},
{
color: 'blue',
value: '#00f',
},
{
color: 'cyan',
value: '#0ff',
},
{
color: 'magenta',
value: '#f0f',
},
{
color: 'yellow',
value: '#ff0',
},
{
color: 'black',
value: '#000',
},
];
const filteredResultsObj = {
color: "red"
}
const filteredData = _.filter(sampleProducts, filteredResultsObj)
console.log(filteredData)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
我只能做一个完整的单词过滤器。关于实施这样的通配符过滤器的任何建议?
const sampleProducts = [{
color: 'red',
value: '#f00',
},
{
color: 'green',
value: '#0f0',
},
{
color: 'blue',
value: '#00f',
},
{
color: 'cyan',
value: '#0ff',
},
{
color: 'magenta',
value: '#f0f',
},
{
color: 'yellow',
value: '#ff0',
},
{
color: 'black',
value: '#000',
},
];
const filteredResultsObj = {color: "bl", value: '#f0'}
const filteredData = _.filter(sampleProducts, filteredResultsObj)
// [{color: 'blue', value: '#00f'}, {color: 'black', value: '#000'}, {
color: 'red',
value: '#f00',
}, {
color: 'magenta',
value: '#f0f',
}]
仅从一开始就应该像上面的示例一样对数据进行过滤。不应在中间使用bl过滤值。谢谢。
答案 0 :(得分:2)
一种解决方案是使用每次迭代调用的函数并测试与您的顾客匹配的正则表达式。在这种情况下,匹配以bl
开头的内容的正则表达式:
const sampleProducts = [
{color: 'red', value: '#f00'},
{color: 'green', value: '#0f0'},
{color: 'blue', value: '#00f'},
{color: 'cyan', value: '#0ff'},
{color: 'magenta', value: '#f0f'},
{color: 'yellow', value: '#ff0'},
{color: 'black', value: '#000'}
];
const regexp = /^bl/;
const filteredData = _.filter(sampleProducts, (o) => o.color.match(regexp));
console.log(filteredData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
答案 1 :(得分:0)
在不使用lodash或下划线的情况下,您的用例可以由此处理
const sampleProducts = [{
color: 'red',
value: '#f00',
},
{
color: 'green',
value: '#0f0',
},
{
color: 'blue',
value: '#00f',
},
{
color: 'cyan',
value: '#0ff',
},
{
color: 'magenta',
value: '#f0f',
},
{
color: 'yellow',
value: '#ff0',
},
{
color: 'black',
value: '#000',
},
];
var strToMatch = 'bl';
var filtered = sampleProducts.filter(function(p) {
var colorArray = p.color.split('');
var colorToMatch = [];
for(var i = 0; i < strToMatch.length; i++) {
colorToMatch.push(colorArray[i]);
}
return strToMatch.toLowerCase() == colorToMatch.join('').toLowerCase()
})
console.log(filtered)
答案 2 :(得分:0)
您可能需要在此处使用RegExp
。
const sampleProducts = [{
color: 'red',
value: '#f00',
},
{
color: 'green',
value: '#0f0',
},
{
color: 'blue',
value: '#00f',
},
{
color: 'cyan',
value: '#0ff',
},
{
color: 'magenta',
value: '#f0f',
},
{
color: 'yellow',
value: '#ff0',
},
{
color: 'black',
value: '#000',
},
];
const filterByValue = (coll, value) =>
_.filter(coll, _.flow(
_.values,
_.partialRight(_.some, _.method('match', new RegExp(value, 'i')))
));
console.log(filterByValue(sampleProducts, 'r'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>