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

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"

回复
阅读 848
2 个回答

先给 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
}))
for(let i=1; i<data.account_list.length; i++){
      const item = data.account_list[i];
      const { account_id, account_name, account_money, account_transaction_sn, account_remark } = item;
      this.settlement_data2.push({
            account_id, 
            account_name, 
            amount_receivable:account_money, 
            transaction_number: account_transaction_sn, 
            remark: account_remark
      })
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏