Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!