Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
How to push data to an object key that may not exist yet in typescript

I have a defined interface here:

interface Notification {
  fullDate: string;
  weekday: string;
  info: {
    title: string;
    subtitle: string;
    read: boolean;
  };
}

Later, I have defined a const that is of that type:

  const orderedNotifications: { [month: string]: Notification[] } = {};

I get the data from outside and use a foreach loop where I get a list of objects with data retrieved from the same months. I want to check if the object has that month as a key and if not, create it and push all the data of similar months to that key. I tried like this:

orderedNotifications[month].push({
  fullDate,
  weekday,
  info,
});

Where month is the variable with the month of the post. Unfortunately, I get a TypeError: Cannot read properties of undefined (reading 'push')

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You are getting TypeError: Cannot read properties of undefined (reading 'push') because month key is not defined within orderedNotifications object.

Use the following code:

// 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,
});
about 4 years ago · Juan Pablo Isaza Relatório

0

Just add an if check and add it if it isn't there already... silly me.

if (!(month in orderedNotifications)) {
      orderedNotifications[month] = [
        {
          fullDate,
          weekday,
          info,
        },
      ];
    } else {
      orderedNotifications[month].push({
        fullDate,
        weekday,
        info,
      });
    }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda