• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

183
Views
How to get value of object property using template strings

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
            }
          },
        },
      },
    };
about 3 years ago · Santiago Trujillo
1 answers
Answer question

0

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
        },
      },
    },
  },
};
about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error