How to get value of object property using template strings

872 Views Asked by At

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

There are 1 best solutions below

2
Bergi On BEST ANSWER

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