请问大家,一般是怎么解决这种报错的?

作者站长头像
站长
· 阅读数 16

settlement_data2:[]

我有个空数组

for(let i=1;i<data.account_list.length;i++){
                        this.settlement_data2[i].account_id = data.account_list[i].account_id
                        this.settlement_data2[i].account_name = data.account_list[i].account_name
                        this.settlement_data2[i].amount_receivable = data.account_list[i].account_money
                        this.settlement_data2[i].transaction_number = data.account_list[i].account_transaction_sn
                        this.settlement_data2[i].remark = data.account_list[i].account_remark
                    }

我想动态给这个settlement_data2 空数组,循环赋值一些属性和值,这回导致Cannot set property 'xxxxxx' of undefined出现类似这种的报错,原因我也知道,因为未定义这些属性,但是我却不知道怎么处理这种比较好,

我不能直接push(data.account_list[i]) 因为这个数据里的一些属性名不是我想要的,

data.account_list 里的属性名是:

account_id: "869"account_money: "33.00"account_name: "微信"account_remark: "85"account_transaction_sn: "8923"

而我想要的是:

account_id: "869"amount_receivable: "33.00"account_name: "微信"remark: "85"transaction_number: "8923"

回复
1个回答
avatar
test
2024-07-18

先给 this.settlement_data2[i] 一个空对象 {},再赋值属性就没问题,另外 i=1 会漏了第一项,得改为 i=0

- for(let i=1;i<data.account_list.length;i++){
+ for(let i=0;i<data.account_list.length;i++){
+   this.settlement_data2[i] = {}
    this.settlement_data2[i].account_id = data.account_list[i].account_id
    ...

可以用 map + 解构来简化代码,比如重命名某些属性

this.settlement_data2 = data.account_list.map(({
  account_money,
  account_transaction_sn,
  account_remark,
  ...rest
}) => ({
  amount_receivable: account_money,
  transaction_number: account_transaction_sn,
  remark: account_remark,
  ...rest
}))
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容