简体   繁体   中英

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. 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:

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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