[英]A better way to deal with objects using many nested forEach?
我想知道在處理具有嵌套 arrays 屬性的對象時是否有更好的方法來處理嵌套的 forEach。
我的 object(總結):
{
...,
"tx_responses": [
{
...
"logs" : [
{
...,
"events": [
{
"type": "coin_received",
"attributes": [
{
"key": "receiver",
"value": "somesome"
},
{
"key": "amount",
"value": "somesome"
}
]
},
...
{
"type": "transfer",
"attributes": [
{
"key": "recipient",
"value": "somesome"
},
{
"key": "sender",
"value": "somesome"
},
{
"key": "amount",
"value": "somesome"
}
]
},
{
"type": "withdraw_rewards",
"attributes": [
{
"key": "amount",
"value": "somesomesomehere"
},
{
"key": "validator",
"value": "somesome"
}
]
},
...
]
}
],
...
我實際上是在嘗試提取"type": "withdraw_rewards"
的"attributes"
數組中的所有{ key: 'amount', value: 'somesomesomehere' }
對象: "events"
數組中的“withdraw_rewards”object。
目前這是我為執行任務而編寫的代碼:
getWithdrawnAmounts: async(del_addr_) => {
let withdrawnAmounts = [];
const res = await axios.get("some_url_that_uses_del_addr_");
res.data.tx_responses.forEach(txr => {
txr.logs.forEach(log => {
log.events.forEach(evnt => {
if (evnt.type == "withdraw_rewards") {
evnt.attributes.forEach(attr => {
if (attr.key == "amount") {
withdrawnAmounts.push(attr);
}
})
}
})
})
});
return withdrawnAmounts;
}
該代碼幫助我獲得我需要的東西,但我想知道是否有更好的方法來編寫我的代碼,這樣我就不必使用這么多嵌套.forEach
方法。 我想知道是否應該使用.flat()
或.flatMap()
但我很想知道人們將如何處理這個問題?
謝謝!
您將不得不為要深入的每個級別調用某種迭代。
現在,有一種更實用的方法來獲取所需的數據,使用flatMap
和filter
:
const data = { "tx_responses": [{ "logs": [{ "events": [{ "type": "coin_received", "attributes": [{ "key": "receiver", "value": "somesome" }, { "key": "amount", "value": "somesome" }]}, { "type": "transfer", "attributes": [{ "key": "recipient", "value": "somesome" }, { "key": "sender", "value": "somesome" }, { "key": "amount", "value": "somesome" }]}, { "type": "withdraw_rewards", "attributes": [{ "key": "amount", "value": "somesomesomehere" }, { "key": "validator", "value": "somesome" }]}]}]}]}; const result = data.tx_responses.flatMap(r => r.logs.flatMap(l => l.events.filter(e => e.type === 'withdraw_rewards').flatMap(e => e.attributes.filter(a => a.key === 'amount')) ) ); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.