我有一个 Angular 服务,它发送一个数据服务调用并返回一个包含多层数据的对象数组。我希望能够过滤该数据并仅返回匹配的记录。
this.behaviourStore.state$ = {
"todos": [
{
"accountNo": "50190000009400",
"vpainfo": [
{
"vpa": "log@bandhan"
}
]
},
{
"accountNo": "10180000025686",
"vpainfo": []
}
]
}
并尝试了以下方式,但收到错误消息, TypeError: Cannot read properties of undefined (reading 'vpainfo')
this.virtualAddressListObj = this.behaviourStore.state$.
pipe(map(state => state.todos.filter((v: any) => (v.vpainfo.length !=0 && v.vpainfo[0].vpa !== null && v.vpainfo[0].vpa !== undefined))));
this.virtualAddressListObj.subscribe(
val => { console.log(JSON.stringify(val))}, //next callback
error => { console.log(error) }, //error callback
() => { console.log("Completed") } //complete callback
)
不确定您是否总是想要获取所有vpainfo
属性,但是,我认为您可以为该过滤操作使用辅助函数:
this.behaviourStore.state$.pipe(
map((response) => this.getPainfo(response['todos']))
).subscribe(
(data) => console.log('my data:', data), // output: my data: ['log@bandhan']
(error) => console.log('Error produced:', error),
() => console.log('Finalized')
);
private getPainfo(dataArray: any[]) {
const result = [];
for (const element of dataArray) {
const keys = Object.keys(element);
for (const key of keys) {
if (key !== 'vpainfo') { continue; }
element[key].filter((e) => e?.vpa ? result.push(e.vpa) : '')
}
}
return result;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句