[英]Dynamically created object returns undefined on attempt to access its key value
[英]dynamically set object value with undefined key
我正在嘗試創建一個沒有任何價值的 object。
for (let i = 0; i < chartyearsale.length; i++) {
var year = chartyearsale[i].year,
grp = chartyearsale[i].family,
qnt = chartyearsale[i].qnt,
qntsk = chartyearsale[i].qntsk,
fat = chartyearsale[i].total;
total[year] = Object.assign({
[grp]: {
val1: (total[year][grp].val1 || 0) + val1,
val2: (total[year][grp].val2 || 0) + val2,
val3: (total[year][grp].val3 || 0) + val3
}
}, total[year]);
}
值“year、group、value1、value2 和 value3”均已定義。
我收到這樣的回復:
Cannot read properties of undefined (reading 'grp')
我認為這應該以不同的方式進行:
(total[year][grp].val1 || 0)
//should return 0 if undefined, but it breaks the script!
您無法訪問不存在的嵌套屬性,即使您將其替換為|| 0
|| 0
在右邊:
const obj = {}; // Forbidden: console.log(obj.foo.bar);
所以做total[year][group].val1
失敗了,因為total
開始時是空的 object。你需要
val1: (total[year]?.[group]?.val1 ?? 0) + value1,
對於所有三個值,使嵌套訪問安全。
更好的方法是,如果您是第一次創建 object:
const total = {
[year]: {
[group]: {
val1: value1,
val2: value2,
val3: value3,
}
}
};
如果屬性可能已經存在:
total[year] ??= {};
total[year][group] ??= {};
const totalGroup = total[year][group];
totalGroup.val1 = (totalGroup.val1 ?? 0) + value1;
totalGroup.val2 = (totalGroup.val2 ?? 0) + value2;
totalGroup.val3 = (totalGroup.val3 ?? 0) + value3;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.