You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从关联数组提取ID生成新数组?解决遍历赋值报错问题

问题:从Proxy对象数组中提取ID生成新数组

原关联数组结构(元素为Proxy对象):

0: Proxy {id: 33, name: 'users.update'}
1: Proxy {id: 32, name: 'users.show'}
2: Proxy {id: 29, name: 'invoice-master.update'}
3: Proxy {id: 27, name: 'collection-deposite.index'}

期望结果:[33,32,29,27](注:原示例结果少写了最后一个ID,解法通用所有元素)

错误代码及问题分析

你尝试的代码:

for (let index in this.singleData.permissions) {
    this.singleData.permissions = this.singleData.permissions[index].id;
}

运行报错:

Uncaught TypeError: Cannot read properties of undefined (reading 'id')

错误原因:
第一次循环时,你把原数组this.singleData.permissions直接覆盖成了第一个元素的id值(33),此时它已经从数组变成了数字类型。第二次循环时,index变为1,尝试访问数字33的[1]属性会得到undefined,再读取.id就触发了类型错误。

而仅打印id的代码能正常运行,是因为没有修改原数组,每次循环都能正确访问数组元素的id。

解决方案

方法1:使用Array.map()(最简洁)

利用数组map方法直接提取每个元素的id,生成新数组:

const ids = this.singleData.permissions.map(item => item.id);
// 结果:[33,32,29,27]

方法2:创建新数组循环添加(兼容更多场景)

如果需要兼容旧环境或自定义逻辑,可创建新数组循环推入id:

const ids = [];
// 推荐用for...of遍历数组元素
for (const item of this.singleData.permissions) {
    ids.push(item.id);
}

// 也可以用for...in(注意数组索引)
for (const index in this.singleData.permissions) {
    ids.push(this.singleData.permissions[index].id);
}

方法3:直接替换原数组(如果需要)

若要把this.singleData.permissions直接替换为ID数组,先提取新数组再赋值:

this.singleData.permissions = this.singleData.permissions.map(item => item.id);

内容的提问来源于stack exchange,提问作者Azim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 18:37:34