我有一个对象数组,想要基于另一个字符串数组的值对其进行过滤,并删除不包含任何字符串的对象。
我尝试对字符串数组使用split并在forEach中搜索每个术语,但是没有用,然后尝试了以下作为过滤器的过滤器,但是它过滤的不是部分完全匹配。
var employees = [
{"name": "zxc asd", "age":"30"},
{"name": "asd", "age":"24"},
{"name": "qwe", "age":"44"},
{"name": "zxc", "age":"28"},
];
var keepNames = ["asd", "qwe"];
keepNames = keepNames.map(name => {
return name.toLowerCase();
});
var filteredEmployees = employees.filter(emp => {
return keepNames.indexOf(emp.name.toLowerCase()) !== -1;
});
console.log( filteredEmployees );
Expected Output[
{"name": "zxc asd", "age":"30"},
{"name": "asd", "age":"24"},
{"name": "qwe", "age":"44"}];
Actual Output [
{"name": "asd", "age":"24"},
{"name": "qwe", "age":"44"}]
非常感谢您的帮助。 预先感谢
答案 0 :(得分:0)
您还需要迭代名称为keep
的数组并检查该值。
var employees = [{ name: "zxc asd", age: "30" }, { name: "asd", age: "24" }, { name: "qwe", age: "44" }, { name: "zxc", age: "28" }],
keep = ["asd", "qwe"],
filtered = employees.filter(({ name }) =>
keep.some(n => name.toLowerCase().includes(n))
);
console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
indexOf
使用strict equality
,因此不会部分匹配。
您可以使用some
和includes
var employees = [ {"name": "zxc asd", "age":"30"},{"name": "asd", "age":"24"},{"name": "qwe", "age":"44"},{"name": "zxc", "age":"28"},];
var filterBy = ["asd", "qwe"];
var filteredEmployees = employees.filter(emp => {
return filterBy.some(v => emp.name.toLowerCase().includes(v.toLowerCase()))
});
console.log(filteredEmployees);