【问题标题】:Filter Substring from JSON in JQuery在 JQuery 中从 JSON 中过滤子字符串
【发布时间】:2023-03-14 22:35:01
【问题描述】:

JSON:

"offers":[
   {
      "loanType":"432321CMP"
   },
   {
      "loanType":"788407CMP"
   },
   {
      "loanType":"97934OOW"
   },
   {
      "loanType":"8293EWC-AS"
   },
   {
      "loanType":"6653EWC-AS"
   }
]

我想根据["EWC-AS", "CMP"]结尾的子串过滤数据

    myArrayFiltered = offers.filter(function(v) {
        return (["EWC-AS"].indexOf(v.loanType)) > -1;
    });

如果我传递确切的值以匹配它可以工作,但对于子字符串它不会。

【问题讨论】:

    标签: javascript jquery json filter frontend


    【解决方案1】:

    Array.prototype.indexOf() 查找完全匹配,而不是子字符串。使用find() 使用回调函数搜索数组,以便您可以指定如何匹配它。并使用String.prototype.includes() 测试子字符串匹配。

    let offers = [{
        "loanType": "432321CMP",
      },
      {
        "loanType": "788407CMP",
      },
      {
        "loanType": "97934OOW",
      },
      {
        "loanType": "8293EWC-AS",
      },
      {
        "loanType": "6653EWC-AS",
      }
    ];
    
    let codes = ["EWC-AS", "CMP"];
    let myArrayFiltered = offers.filter(o => codes.find(s => o.loanType.includes(s)));
    
    console.log(myArrayFiltered);

    【讨论】:

      【解决方案2】:

      您可以使用 filter 结合 findendsWith 来过滤它,以检查子字符串是否位于字符串的末尾。

      const codes = ["EWC-AS", "CMP"];
      const myArrayFiltered = bla.offers.filter(x => codes.find(z => x.loanType.endsWith(z)));
      

      const bla = {
        "offers": [{
            "loanType": "432321CMP",
          },
          {
            "loanType": "788407CMP",
          },
          {
            "loanType": "97934OOW",
          },
          {
            "loanType": "8293EWC-AS",
          },
          {
            "loanType": "6653EWC-AS",
          },
          {
            "loanType": "EWC-AS6653",
          }
        ]
      };
      
      const codes = ["EWC-AS", "CMP"];
      const myArrayFiltered = bla.offers.filter(x => codes.find(z => x.loanType.endsWith(z)));
      console.log(myArrayFiltered);

      【讨论】:

        猜你喜欢
        • 2017-03-03
        • 2018-09-12
        • 1970-01-01
        • 1970-01-01
        • 2018-09-28
        • 2013-08-12
        • 1970-01-01
        • 1970-01-01
        • 2019-09-21
        相关资源
        最近更新 更多