Template String As Object Property Name
Why are template strings not allowed as literal object keys?
Template strings are expressions, not literals1. You can only use string literals (and identifiers) for property names, for everything else - that is not known to be static - you need a computed property name.
Is it for performance reasons?
No, that's unlikely. It's to ease parsing, and makes it easy to distinguish constant (statically known) property names from dynamically computed ones.
And mostly, it's a feature that no one needs. It doesn't simplify or shorten anything, and what you would achieve with it is already possible.
Will the syntax be allowed sometime in the future?
Nope.
1: Even when they're called "template literals", technically they aren't literals. And: templates don't even need to be strings, they can evaluate to anything.
Can I use Template String on object key in ES6?
You have to use computed property syntax:
const key = 'my-key', value = 'my-value'
const obj = {
[`${key}`]: value
}
Note that if you just want to use a variable as key, you can write [key]: value
.
How to get value of object property using template strings
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
},
},
},
},
};
How to use template literal as key inside object literal?
And of course I come up with a solution straight away:
{
[`${id}_name`]: "John Doe",
[`${id}_age`]: 27,
}
Wrap the template literal in square brackets. This will evaluate the expression in between the square brackets and use it as the key.
Without square brackets, only identifiers (e.g. my_key_name
), single or double quote strings (e.g. "My Key Name"
) and numbers (e.g. 42
) can be used.
Property assignment expected when using template literals to create an Object
Go back to what you had first:
let object = {};
And after you have populated the object, wrap it using computed property name syntax:
return JSON.stringify({ [form.name]: object });
Replace keys in template string with object properties
You can use replace
with a callback :
var optionString = templateString.replace(/{(\w+)}/g, function(_,k){
return obj[k];
});
Demonstration
Related Topics
Activexobject in Firefox or Chrome (Not Ie!)
Caching a Promise Object in Angularjs Service
Rails - Could Not Find a JavaScript Runtime
Vanilla JavaScript Event Delegation
Differencebetween JavaScript Promises and Async Await
Disable Submit Button on Form Submit
Keyboard Shortcuts with Jquery
What Does [Object Object] Mean? (Javascript)
How to Use Redirect in Version 5 of React-Router-Dom of Reactjs
How to Set Default Homepage in Ff and Chrome via JavaScript
Best Way to Get the Key of a Key/Value JavaScript Object
Js:Convert Array of Strings to Array of Objects
React-Router: No Not Found Route
Why Does a String Index in an Array Not Increase the 'Length'