Home > Blockchain >  How to push data to an object key that may not exist yet in typescript
How to push data to an object key that may not exist yet in typescript

Time:10-07

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')

CodePudding user response:

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,
});

CodePudding user response:

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,
      });
    }
  • Related