为rxjs在angular中使用嵌套对象进行深度嵌套过滤提供建议?

cczfrluj  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(358)

快速问题:
对不起,我对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与用户提供的特定字符串相匹配(例如workhead.code=='cs2230'),获得数组中的相关json对象?
谢谢你的帮助。

vd2z7a6w

vd2z7a6w1#

你不清楚你到底想要什么。我假设您希望返回完整的对象,而不仅仅是内部对象 "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

相关问题