JavaScript解构proposal对象嵌套stakes数组的entity.id报错求解
报错根因
你使用的对象解构语法默认将stakes当做普通对象处理,但你已经确认stakes是数组类型,数组本身不存在entity属性,因此读取stakes.entity返回undefined,进一步读取id就会抛出类型错误。
解决方案
直接遍历stakes数组提取每个元素下的entity.id即可,实现代码如下:
基础版(适用于所有stake元素都存在有效entity和id的场景)
const supporterIds = proposal.stakes.map(stake => stake.entity.id)
兼容版(避免部分元素缺失字段引发报错)
如果存在部分stake没有entity或者id的情况,可以加可选链和空值过滤:
const supporterIds = proposal.stakes .map(stake => stake?.entity?.id) .filter(Boolean) // 自动过滤undefined、null等无效值,确保返回的id列表全部可用
原代码问题补充
你之前写的解构逻辑const {stakes: {entity}, }= proposal等价于执行const entity = proposal.stakes.entity,数组没有entity这个键,自然返回undefined。如果仅需要提取数组第一个元素的id,也可以用数组解构的写法:
// 仅适用于提取第一个stake的entity id场景 const { stakes: [ { entity: { id: firstSupporterId } } ] } = proposal
内容的提问来源于stack exchange,提问作者Striker
相关产品推荐
相关产品推荐

