【问题标题】:Advice for deeply nested filtering with nested object for RXJS in angular?使用角度的 RXJS 嵌套对象进行深度嵌套过滤的建议?
【发布时间】:2021-10-02 21:02:04
【问题描述】:

快速提问:

对不起,我对 Typescipt 和 RxJS 还很陌生。我有以下 JSON:

[
{
    "ID": "",
    "UEN": "",
    "Name": "",
    "Address": "",
    "Telephone": "",
    "Fax": "",
    "Email": "",
    "Website": "",
    "Postal": "",
    "Status": ,
    "TimeCreated": ,
    "TimeUpdated": ,
    "Workheads": [{
            "ID": "",
            "Name": "",
            "Code": ""
        },
        {
            "ID": "",
            "Name": "",
            "Code": ""
        }
    ]
},
...
]

这个 json 通过 HTTP get() 的 Observable 输入到我的 Angular 应用程序中。

我如何过滤 workhead.Code 部分,以便我可以通过匹配内部 workhead.Code 来获得数组中的那些相关 Json 对象 strong> 到用户提供的特定字符串(例如 workhead.Code == 'CS2230')?

帮助表示赞赏。

【问题讨论】:

    标签: javascript arrays typescript rxjs filtering


    【解决方案1】:

    你并不清楚你想要返回什么。我假设您希望返回完整的对象,而不仅仅是内部的"Workheads"。您可以使用filter() 来获得您想要的:

    const data = [{
      "ID": "",
      "UEN": "",
      "Name": "",
      "Address": "",
      "Telephone": "",
      "Fax": "",
      "Email": "",
      "Website": "",
      "Postal": "",
      "Status": "",
      "TimeCreated": "",
      "TimeUpdated": "",
      "Workheads": [{
        "ID": "",
        "Name": "",
        "Code": "abc"
      }, {
        "ID": "",
        "Name": "",
        "Code": "def"
      }]
    }];
    
    // Returns an array of the objects which contain matching code.
    const getRelatedByCode = (arr, userProvidedCode) => {
      return arr.filter((i) => {
        return (i.Workheads || [])
          .some(wh => wh.Code === userProvidedCode);
      });
    }
    
    console.log(getRelatedByCode(data, 'abc')); // Returns array with the object
    console.log(getRelatedByCode(data, 'zzz')); // Returns empty array

    【讨论】:

    • @Spectric,非常感谢您的帮助。真的很感激。 :)
    • @Spectric,如果 filter 是 string[] 而不是 string,会发生什么?
    • @Kim 你应该感谢 dacodr。他是发布答案的人,我只是编辑了它:)
    猜你喜欢
    • 2019-01-29
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 2017-06-27
    • 2020-09-24
    • 2021-01-27
    相关资源
    最近更新 更多