简体   繁体   English

根据字符串数组过滤对象数组

[英]Filter an array of objects against array of strings

That returns an empty array.这将返回一个空数组。 I have also tried using the array of selectedRules[0] itself but got same result.我也尝试过使用selectedRules[0]本身的数组,但得到了相同的结果。 How can we do the comparison of filter on an array of objects against an array of strings to return an array of objects with each filtered rule?我们如何将对象数组上的过滤器与字符串数组进行比较,以返回具有每个过滤规则的对象数组?

   const allRules = [
      {
       RuleName: "Two",
      RuleId: 2
        },
        {
          RuleName: "Three",
         RuleId: 3
        },
      {
        RuleName: "Four",
        RuleId:4
      }
    ];

    const selectedRules = ["2", "3"]

    const filteredRule = allRules.filter(x => x.RuleId === selectedRules)

    console.log(filteredRule) // []

You need to你需要

  • Convert the rules to the same type so that comparison works (a string won't be === to a number)将规则转换为相同的类型,以便比较有效(字符串不会===为数字)
  • Check whether the selectedRules array .includes the RuleId value being iterated over:检查selectedRules数组是否RuleId .includes

 const allRules = [{ RuleName: "Two", RuleId: 2 }, { RuleName: "Three", RuleId: 3 }, { RuleName: "Four", RuleId: 4 } ]; const selectedRules = ["2", "3"] const filteredRule = allRules.filter(x => selectedRules.includes(String(x.RuleId))) console.log(filteredRule)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM