根据字符串数组“具有部分匹配”来过滤对象数组

时间:2019-10-05 16:48:34

标签: javascript arrays typescript

我有一个对象数组,想要基于另一个字符串数组的值对其进行过滤,并删除不包含任何字符串的对象。

我尝试对字符串数组使用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"}]

非常感谢您的帮助。 预先感谢

2 个答案:

答案 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,因此不会部分匹配。

您可以使用someincludes

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);