gpt4 book ai didi

javascript - Lodash 帮助使用搜索词和多个属性名称进行过滤

转载 作者:行者123 更新时间:2023-12-03 07:17:34 24 4
gpt4 key购买 nike

我希望搜索多列,但是我在互联网上找到的所有代码都仅限于搜索多列的单个搜索词。我希望通过多个搜索词过滤多列

数据:

var propertynames = ['firstName','lastName'];
var data = [
{
"city":"Irwin town",
"address":"1399 Cecil Drive",
"lastName":"Auer",
"firstName":"Wanda"
},
{
"city":"Howell haven"
"address":"168 Arnoldo Light"
"lastName":"Balistreri",
"firstName":"Renee"
}
];
var searchTerm = 'Wanda Auer';

应该生成一个过滤掉第二个对象的数组。谢谢!

最佳答案

我为您的问题创建了两种解决方案。第一个是完全按照您的需要进行:按两个字段过滤集合。第二个更灵活,因为它允许按任意多个字段进行过滤。

第一个解决方案:

function filterByTwoFields(coll, searchFilter) {
return _.filter(coll, function(item) {
return (item.firstName + ' ' + item.lastName) === searchTerm;
});
}

var data = [
{
"city":"Irwin town",
"address":"1399 Cecil Drive",
"lastName":"Auer",
"firstName":"Wanda"
},
{
"city":"Howell haven",
"address":"168 Arnoldo Light",
"lastName":"Balistreri",
"firstName":"Renee"
}
];
var searchTerm = 'Wanda Auer';

var result = filterByTwoFields(data, searchTerm);
alert(JSON.stringify(result));
<script src="https://raw.githubusercontent.com/lodash/lodash/master/dist/lodash.min.js"></script>

第二个解决方案:

function filterByMultipleFields(coll, filter) {
var filterKeys = _.keys(filter);
return _.filter(coll, function(item) {
return _.every(filterKeys, function(key) {
return item[key] === filter[key];
});
});
}

var data = [
{
"city":"Irwin town",
"address":"1399 Cecil Drive",
"lastName":"Auer",
"firstName":"Wanda"
},
{
"city":"Howell haven",
"address":"168 Arnoldo Light",
"lastName":"Balistreri",
"firstName":"Renee"
}
];

var filter = {
firstName: 'Wanda',
lastName: 'Auer'
}
var result = filterByMultipleFields(data, filter);
alert(JSON.stringify(result));
<script src="https://raw.githubusercontent.com/lodash/lodash/master/dist/lodash.min.js"></script>

关于javascript - Lodash 帮助使用搜索词和多个属性名称进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36353855/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com