How to use template literal as key inside object literal? [duplicate] - javascript

This question already has answers here:
Template String As Object Property Name
(3 answers)
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 3 years ago.
How do I use template literal as key inside object literal?
The following code:
{
`${id}_name`: "John Doe",
`${id}_age`: 27,
}
Produces a syntax error:
Uncaught SyntaxError: Unexpected token :
Is there something I'm missing, or is this not supported? If not, is support for this feature planned?

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.

Your answer is correct, but i will try to answer the why of it.
If we refer to the Ecmascript object definition, it is said
Properties are identified using key values. A property key value is either an ECMAScript String value or a Symbol value. All String and Symbol values, including the empty String, are valid as property keys. A property name is a property key that is a String value.
In this case, a ECMAScript string is defined as
A string literal is zero or more Unicode code points enclosed in single or double quotes. Unicode code points may also be represented by an escape sequence. All code points may appear literally in a string literal except for the closing quote code points, U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE RETURN), and U+000A (LINE FEED).
Which mean a string has to be unicode caracter enclosed in single or double quotes. And Object keys must be ECMAScript string or Symbol, which i assume are index.
A template literal is a ECMAScript string but an ECMAScript string is not a template literal.
P.S. Take this with a grain of salt, i'm not an ECMAScript expert but that's what i could find.

Related

how to access json field with "-" e.g. 'data-id': 'smth' [duplicate]

This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
How do I reference a JavaScript object property with a hyphen in it?
(11 answers)
Closed 3 months ago.
I am unable to retrieve a value from a json object when the string has a dash character:
{
"profile-id":1234, "user_id":6789
}
If I try to reference the parsed jsonObj.profile-id it returns ReferenceError: "id" is not defined but jsonObj.user_id will return 6789
I don't have a way to modify the values being returned by the external api call and trying to parse the returned string in order to remove dashes will ruin urls, etc., that are passed as well. Help?
jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).
To access a key that contains characters that cannot appear in an identifier, use brackets:
jsonObj["profile-id"]
In addition to this answer, note that in Node.js if you access JSON with the array syntax [] all nested JSON keys should follow that syntax
This is the wrong way
json.first.second.third['comment']
and will will give you the 'undefined' error.
This is the correct way
json['first']['second']['third']['comment']
For ansible, and using hyphen, this worked for me:
- name: free-ud-ssd-space-in-percent
debug:
var: clusterInfo.json.content["free-ud-ssd-space-in-percent"]
For anyone trying to apply the accepted solution to HomeAssistant value templates, you must use single quotes if you are nesting in doubles:
value_template: "{{ value_json['internet-computer'].usd }}"
If you are in Linux, try using the following template to print JSON value which contains dashes '-'
jq '.["value-with-dash"]'
It worked for me.

Javascript Invalid left-hand side in assignment expression when renaming [duplicate]

This question already has answers here:
How do I reference a JavaScript object property with a hyphen in it?
(11 answers)
Closed 4 years ago.
I have some code which is giving me the following error when I rename a class name.
This gives no error:
this.container = document.createElement("ul"),
But when I rename the container class name to this:
this.tt-container = document.createElement("ul"),
I get the following error:
Syntax error: Invalid left-hand side in assignment expression
How can I fix this?
use _ instead of -, so this.tt_container, not this.tt-container
From MDN,
An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation.
In your case - is not a valid JavaScript identifier. To use -, Use Bracket Notation
this["tt-container"] = document.createElement("ul"),

How to get "#" from JSON [duplicate]

This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
How do I reference a JavaScript object property with a hyphen in it?
(11 answers)
Closed 3 months ago.
I am unable to retrieve a value from a json object when the string has a dash character:
{
"profile-id":1234, "user_id":6789
}
If I try to reference the parsed jsonObj.profile-id it returns ReferenceError: "id" is not defined but jsonObj.user_id will return 6789
I don't have a way to modify the values being returned by the external api call and trying to parse the returned string in order to remove dashes will ruin urls, etc., that are passed as well. Help?
jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).
To access a key that contains characters that cannot appear in an identifier, use brackets:
jsonObj["profile-id"]
In addition to this answer, note that in Node.js if you access JSON with the array syntax [] all nested JSON keys should follow that syntax
This is the wrong way
json.first.second.third['comment']
and will will give you the 'undefined' error.
This is the correct way
json['first']['second']['third']['comment']
For ansible, and using hyphen, this worked for me:
- name: free-ud-ssd-space-in-percent
debug:
var: clusterInfo.json.content["free-ud-ssd-space-in-percent"]
For anyone trying to apply the accepted solution to HomeAssistant value templates, you must use single quotes if you are nesting in doubles:
value_template: "{{ value_json['internet-computer'].usd }}"
If you are in Linux, try using the following template to print JSON value which contains dashes '-'
jq '.["value-with-dash"]'
It worked for me.

Access Javascript Object Key with special symbol [duplicate]

This question already has answers here:
Unable to access JSON property with "-" dash [duplicate]
(5 answers)
Closed 5 years ago.
var obj = {
a?: "abc"
}
Want to access Key Which is Not in a valid format.
Giving me Error.
I'm accessing it like this obj.a.
and this is throwing an error.
const obj = { a?: 'aaa' }
console.log(obj.a)
This could work (not tested)
obj['a?'];
Valid property names
Looking at the ECMAScript spec grammar, we can see that a property
name can be either an identifier name (i.e. identifiers + reserved
words), a string literal, or a numeric literal.
Identifier names are a superset of identifiers; any valid identifier
and any reserved word is a valid identifier name.
[...]
When can the quotes be omitted?
Unless an object key is a numeric literal or a valid identifier name,
you need to quote it to avoid a syntax error from being thrown. In
other words, quotes can only be omitted if the property name is a
numeric literal or a valid identifier name. Of course, if the property
name is a string literal, it’s already quoted by definition
source: https://mathiasbynens.be/notes/javascript-properties
To solve your specific issue you can use quotes:
var obj = {
'a?': "abc"
}
obj['aj']
Full answer can be found at
https://stackoverflow.com/a/9571440/1211174
The key should be a simple string in JavaScript, so if you change from a? to a, it should work.

Is there any functional difference between using and not using quotes with javascript property name assignments? [duplicate]

This question already has answers here:
What is the difference between object keys with quotes and without quotes?
(5 answers)
Closed 5 years ago.
I'm not sure of the exact wording to use, but I have seen object assignments in javascript done two wasy
$('#test').dataTable({ fnInitComplete: myFunction });
and
$('#test').dataTable({ "fnInitComplete": myFunction });
Is there any actual difference between these, or any gotchas to be aware of?
There is no difference.
However, if the key is not a valid identifier (eg, it's a keyword, or it has spaces or punctuation), quotes are required.
Also, the JSON standard (which is not Javascript) always requires double-quotes.
The currently accepted answer is incorrect:
However, if the key is not a valid identifier (eg, it's a keyword, or it has spaces or punctuation), quotes are required.
The quotes aren’t required if you use a numeric literal as a property name. Also, keywords and reserved words are valid identifier names, and all identifier names (not just identifiers) are valid JavaScript property names.
From Unquoted property names / object keys in JavaScript, my write-up on the subject:
Quotes can only be omitted if the property name is a numeric literal or a valid identifier name.
[…]
Bracket notation can safely be used for all property names.
[…]
Dot notation can only be used when the property name is a valid identifier name.
I also made a tool that will tell you if any given property name can be used without quotes and/or with dot notation. Try it at mothereff.in/js-properties.
The main difference is that with quotes, you can use keys with spaces, js keywords, etc that are illegal as normal symbols. That's why JSON requires them.
Without the quotes, the property name must be either a number, or a valid JavaScript identifier. With the quotes, you can use an arbitrary string. Quoting a string that's already a valid JS identifier is functionally identical to using just the identifier.

Categories