我希望遍历array
的{{1}},为便于说明,此处为objects
。我想使用提供的搜索词和每个Users
属性的值来过滤那些Users
。
我想出了以下可行的解决方案,但是,我想看看是否有人有更优雅的方法?
objects
[编辑]
我不对对象上任何字段的结构,名称或数量做任何假设,因此,我不想使用诸如let users = [
{
first_name: "Super",
last_name: "User"
},
{
first_name: "Admin",
last_name: "Istrator"
}
];
function filterObjects(collection, term) {
let filtered = [];
_.each(collection, obj => {
_.forOwn(obj, (value, key) => {
if (value.includes(term)) {
filtered.push(obj);
}
});
});
return filtered;
}
console.log(filterUsers(users, "Su"));
之类的东西。
答案 0 :(得分:1)
您可以过滤并使用_.some()
来迭代值,并使用Array.includes()
(或等效的破折号)检查值中是否存在该术语。
const filterUsers = (collection, term) =>
collection.filter(o => _.some(o, v => v.includes(term)));
const users = [{"first_name":"Super","last_name":"User"},{"first_name":"Admin","last_name":"Istrator"}];
console.log(filterUsers(users, "Su"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
和使用lodash/fp的想法相同:
const { filter, some, includes } = _;
const filterUsers = term => filter(some(includes(term)));
const users = [{"first_name":"Super","last_name":"User"},{"first_name":"Admin","last_name":"Istrator"}];
console.log(filterUsers("Su")(users));
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
答案 1 :(得分:-2)
没有第三方库的解决方案可能是:
var term = 'Su';
var filtered = users.filter(({first_name, last_name}) => {
return (first_name.includes(term) || last_name.includes(term));
});
console.log(filtered);
希望对您有帮助。