Tengo una interfaz definida aquí:
interface Notification { fullDate: string; weekday: string; info: { title: string; subtitle: string; read: boolean; }; }Posteriormente, he definido una const que es de ese tipo:
const orderedNotifications: { [month: string]: Notification[] } = {};Obtengo los datos del exterior y uso un ciclo foreach donde obtengo una lista de objetos con datos recuperados de los mismos meses. Quiero verificar si el objeto tiene ese mes como clave y, si no, crearlo y enviar todos los datos de meses similares a esa clave. Intenté así:
orderedNotifications[month].push({ fullDate, weekday, info, }); Donde month es la variable con el mes de la publicación. Desafortunadamente, obtengo un TypeError: No se pueden leer las propiedades de undefined (leyendo 'push')
TypeError: Cannot read properties of undefined (reading 'push') porque la clave del month no está definida dentro del objeto orderedNotifications .
Usa el siguiente código:
// This line will solve your issue as it is // checking if the key already exist do nothing // otherwise set empty array on it. orderedNotifications[month] = orderedNotifications[month] || []; orderedNotifications[month].push({ fullDate, weekday, info, });Simplemente agregue un cheque si y agréguelo si aún no está allí ... tonto.
if (!(month in orderedNotifications)) { orderedNotifications[month] = [ { fullDate, weekday, info, }, ]; } else { orderedNotifications[month].push({ fullDate, weekday, info, }); }