Estoy tratando de crear un objeto que no tiene ningún valor.
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]); }Los valores "año, grupo, valor1, valor2 y valor3" están todos definidos.
Estoy recibiendo esta respuesta:
Cannot read properties of undefined (reading 'grp')Creo que esto debería hacerse de otra manera:
(total[year][grp].val1 || 0) //should return 0 if undefined, but it breaks the script!No puede acceder a una propiedad anidada que no existe, incluso si la alterna con || 0 en el lado derecho:
const obj = {}; // Forbidden: console.log(obj.foo.bar); Así que hacer total[year][group].val1 falla, porque total comienza como el objeto vacío. Necesitas
val1: (total[year]?.[group]?.val1 ?? 0) + value1,para los tres valores, para que el acceso anidado sea seguro.
Un mejor enfoque sería, si está creando el objeto por primera vez:
const total = { [year]: { [group]: { val1: value1, val2: value2, val3: value3, } } };Si es posible que las propiedades ya existan:
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;