简体   繁体   中英

Advice for deeply nested filtering with nested object for RXJS in angular?

Quick Question:

Pardon me, I'm fairly new to Typescipt & RxJS. I have the following JSON:

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

This json is feed into my angular app via Observable from HTTP get().

How do I filter the workhead.Code section such that I could get those relevant Json objects within the array by matching the inner workhead.Code to a specific string that has been provided by the user (eg workhead.Code == 'CS2230')?

Help appreciated.

You are not clear exactly what you want returned. I assume you want the full objects returned, and not only the inner "Workheads" . You can use a filter() to get what you want:

 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

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