2

I have this object totalData which I am destructuring to add on a new object value. I understand I am able to define new object properties using template strings (as shown below) but how can I use template strings to get an objects value? The code below just runs an error saying "identifier expected" after the .[${currentMonth}] for example. Is there another way of doing this?

const newTotalData = {
      ...totalData,
      [`${currentYear}`]: {
        [`${currentMonth}`]: {
          [`${currentWeek}`]: {
            [`${currentDay}`]: {
              completedTasks: totalData[`${currentYear}`].[`${currentMonth}`].[`${currentWeek}`].[`${currentDay}`].completedTasks + 1
            }
          },
        },
      },
    };
Brian Mason
  • 85
  • 1
  • 9
  • Is `currentMonth` undefined? It's hard to tell given the current code provided – Dom Jul 25 '22 at 22:31
  • 2
    There's no destructuring in your code, just some object literals – Bergi Jul 25 '22 at 22:38
  • 1
    @Dom sorry for not clarifying, the currentMonth is undefined. How can I add some sort of null/undefined checker? Anytime I try and do so it just prints cannot read properties of undefined. – Brian Mason Jul 25 '22 at 23:30

1 Answers1

1

The problem is not with the template strings, it's the .[…] syntax that you are using. Use either dot or bracket notation, not both at once:

completedTasks: totalData[`${currentYear}`][`${currentMonth}`][`${currentWeek}`][`${currentDay}`].completedTasks + 1

However, notice that the use of template literals in your code is pointless. Property keys are already implicitly coerced to strings, no need to put your variables in template literals that add nothing. Just write

const newTotalData = {
  ...totalData,
  [currentYear]: {
    [currentMonth]: {
      [currentWeek]: {
        [currentDay]: {
          completedTasks: totalData[currentYear][currentMonth][currentWeek][currentDay].completedTasks + 1
        },
      },
    },
  },
};
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Ah I see thank you. My issue is that originally this property does not exist. When I try and perform the solution stated above, I get a properties of undefined error. Is there any way I could get around this? – Brian Mason Jul 25 '22 at 23:33
  • 1
    Did you mean to use optional chaining? The syntax for that is `totalData?.[currentYear]?.[currentMonth]?.[currentWeek]?.[currentDay]?.completedTasks` – Bergi Jul 26 '22 at 03:14