gpt4 book ai didi

javascript - 仅当值不存在时才向对象添加新的数组条目

转载 作者:行者123 更新时间:2023-12-02 23:03:27 27 4
gpt4 key购买 nike

我编写了以下代码来存储数据检索值并将数据存储到对象中:

var contract = new web3.eth.Contract(contractAbi, contractAddress);
var accounts = {};
var balance = {};


// Crawl the Chain from the Contract Deployment Date till the latest block
contract.getPastEvents(
'Transfer',
{
fromBlock: 8437000,
toBlock: 'latest'
},(error, events) => {

if (!error){
var obj=JSON.parse(JSON.stringify(events));

for (const [key, val] of Object.entries(obj)) {
accounts[val.blockNumber] = {
_from: val.returnValues._from,
_to: val.returnValues._to,
_value: parseInt(val.returnValues._value, 10)
// _value: val.returnValues._value
};
}

}
else {
console.log(error)
}

Object.entries(accounts).forEach(([key, val]) => console.log(key, val));

})

这工作正常,其输出是:

8441134 { _from: '0x34872874b65E12408eC0265E9cf0a35FA6c8D13E',
_to: '0x39BC998bD7DC71885661B1062CC2baa9fbe94F45',
_value: 76470000000000000000 }
8441135 { _from: '0x85C5c26DC2aF5546341Fc1988B9d178148b4838B',
_to: '0x2E642b8D59B45a1D8c5aEf716A84FF44ea665914',
_value: 947018889517274100000 }
8441142 { _from: '0xda7C4aAb9bb74710498485ed01CB4D521f7b4456',
_to: '0x24fa98CA3aB52D8CF562B641AbC4b12861e991Cf',
_value: 321279880100000000000 }
8441157 { _from: '0x46340b20830761efd32832A74d7169B29FEB9758',
_to: '0xeE7D76D5B00A10B49e37a9e26a7678be1EE607F4',
_value: 29500000000000000000 }
8441167 { _from: '0x2baa435Ca4B9dE4a135cAE11f4c04C4a1d334089',
_to: '0x9fa7f05C9AaE89752fa9273CFAcADF602657599d',
_value: 1.5043600286e+21 }

我想将其转换为一种格式,其中每个帐户(_to 和 _from)并作为帐户添加到 block 上的索引中,即

// The _to and _from fields become account entries
8441142 { Accounts: '0xda7C4aAb9bb74710498485ed01CB4D521f7b4456',
'0x24fa98CA3aB52D8CF562B641AbC4b12861e991Cf'}
// Add accounts that did not previously exist, ignore ones already in here
8441157 { Accounts: 0xda7C4aAb9bb74710498485ed01CB4D521f7b4456',
'0x24fa98CA3aB52D8CF562B641AbC4b12861e991Cf', '0x46340b20830761efd32832A74d7169B29FEB9758','0xeE7D76D5B00A10B49e37a9e26a7678be1EE607F4'}
// Add accounts that did not previously exist, ignore ones already in here
8441167 { Accounts: '0x2baa435Ca4B9dE4a135cAE11f4c04C4a1d334089','0x9fa7f05C9AaE89752fa9273CFAcADF602657599d'}

我希望能得到关于如何有效地做到这一点的指导。

最佳答案

在循环外部使用变量来保存前一个 block 中的帐户列表。复制它并将新帐户推送到它上面。

  let last_accounts = [];
for (const [key, {blockNumber, returnValues: {_from, _to}}] of Object.entries(obj)) {
let these_accounts = last_accounts.slice(); // copy accounts from previous block
if (!these_accounts.includes(_from)) {
these_accounts.push(_from);
}
if (!these_accounts.includes(_to)) {
these_accounts.push(_to);
}
accounts[blockNumber] = {Accounts: these_accounts};
last_accounts = these_accounts;
}

关于javascript - 仅当值不存在时才向对象添加新的数组条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57700852/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com