[英]how to get the first item in nested, filtered array in javascirpt
我有一个数组:
const aContracts = [[ '0x8ae127d224094cb1b27e1b28a472e588cbcc7620', 0 ],
[ '0xcbf4ab00b6aa19b4d5d29c7c3508b393a1c01fe3', 0 ],
[ '0x03cd191f589d12b0582a99808cf19851e468e6b5', 0 ],
[ '0x0b3f868e0be5597d5db7feb59e1cadbb0fdda50a', 1 ]]
我正在尝试使用每个子数组中的第二项进行过滤。 所以我用:
const aGoodContracts = aContracts.filter(contracts => contracts[1]===1);
我得到:
[["0x0b3f868e0be5597d5db7feb59e1cadbb0fdda50a", 1]]
但是,我想要[编辑我想要所有“好”合同的数组]:
"0x0b3f868e0be5597d5db7feb59e1cadbb0fdda50a"
所以我尝试了一个我在这里找到的解决方案: const aGoodContracts = aContracts.map(k => k.filter(contracts => contracts[1]===1));
但我得到:
[[], [], [], []]
我错过了什么?
只需map()
您的结果即可挑选出数组中的第一个元素。 这将为您留下一个数组,如果您只想要第一个值(如您的预期输出),请获取零索引元素。
const aContracts = [[ '0x8ae127d224094cb1b27e1b28a472e588cbcc7620', 0 ], [ '0xcbf4ab00b6aa19b4d5d29c7c3508b393a1c01fe3', 0 ], [ '0x03cd191f589d12b0582a99808cf19851e468e6b5', 0 ], [ '0x0b3f868e0be5597d5db7feb59e1cadbb0fdda50a', 1 ]] const aGoodContracts = aContracts.filter(contracts => contracts[1]===1).map(c => c[0]); console.log(aGoodContracts); console.log(aGoodContracts[0]);
你可以试试这个
const aContracts = [[ '0x8ae127d224094cb1b27e1b28a472e588cbcc7620', 0 ],
[ '0xcbf4ab00b6aa19b4d5d29c7c3508b393a1c01fe3', 0 ],
[ '0x03cd191f589d12b0582a99808cf19851e468e6b5', 0 ],
[ '0x0b3f868e0be5597d5db7feb59e1cadbb0fdda50a', 1 ]]
const aGoodContracts = aContracts.filter(contracts => contracts[1]===1)[0]
console.log(aGoodContracts[0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.