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

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"


回答:

先给 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

})

}

以上是 请问大家,一般是怎么解决这种报错的? 的全部内容, 来源链接: utcz.com/p/932979.html

回到顶部