[英]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.