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