Create object literal with keys that aren’t valid identifiers [duplicate] - javascript

This question already has answers here:
Why add singe quote to a object's property [duplicate]
(2 answers)
Closed 4 years ago.
In my object literals, I would like to create keys that would not be valid identifiers in order to generate a JSON file like the one in the picture, using JavaScript.
Is it possible to create the object like the following?
var objet = {
targets: [
new Stage(),
{
isStage: false,
name: "Sprite1",
blocks: {
o7d.+f~]6/Bs|=|c/F(=: "Hello"
}
}
]
};
This is what the JSON file looks like:

Yes, you can:
const data = {
blocks: {
"o7d.+f~]6/Bs|=|c/F(=": "Hello"
}
}
console.log(data)
But please be careful what exactly you are doing, because you loose readability with this keys naming.

For understanding purpose, I have picked a sub-set of the object.
You can try following
var blocks = {
"o7d.+f~]6/Bs|=|c/F(=": "Hello" // surround key with quotes
};
console.log(blocks["o7d.+f~]6/Bs|=|c/F(="]); // use bracket notation to fetch

You can use the ES6 feature objet litteral dynamic key:
const illegalKey = 'o7d.+f~]6/Bs|=|c/F(=';
...
blocks: {
[illegalKey]: "Hello"
}
Or just:
blocks: {
'o7d.+f~]6/Bs|=|c/F(=': "Hello"
}

Related

What does an expression consisting of comma-separated variables inside curly braces mean? (Javascript) [duplicate]

This question already has answers here:
What does this symbol mean in JavaScript?
(1 answer)
Javascript object literal: what exactly is {a, b, c}?
(3 answers)
Closed last month.
I'm trying to decipher some code and I stumbled upon this:
var disabled = mswDisabledValue === 'true' ? true : false;
var serviceWorkers = JSON.parse("[{\"scope\":\"/\",\"serviceWorkerUrl\":\"/uxsw/scope/root.js\"},{\"scope\":\"/x\",\"serviceWorkerUrl\":\"/uxsw/scope/now_x.js\"},{\"scope\":\"/now\",\"serviceWorkerUrl\":\"/uxsw/scope/now_x.js\"}]");
var SERVICE_WORKER_MANAGER_CONFIG = { disabled, serviceWorkers };
What does the third line mean?
I tried printing SERVICE_WORKER_MANAGER_CONFIG, and it returned an object:
{
disabled: false,
serviceWorkers: [{
scope: '/',
serviceWorkerUrl: '/uxsw/scope/root.js'
},
{
scope: '/x',
serviceWorkerUrl: '/uxsw/scope/now_x.js'
},
{
scope: '/now',
serviceWorkerUrl: '/uxsw/scope/now_x.js'
}
]
}
Seems like I can declare an object using variables instead of key/value pairs, but I haven't found this documented anywhere. Is this the correct usage of JavaScript?
The line
var SERVICE_WORKER_MANAGER_CONFIG = {disabled, serviceWorkers};
is a valid javascript object initializer. It is also called "Object literal syntax" and it is used as a shorthand for initializing JSON objects. It is identical to calling:
var SERVICE_WORKER_MANAGER_CONFIG = {disabled : disabled, serviceWorkers : serviceWorkers};
More information and examples can be found on MDN.

How to access nested object with numeric key? [duplicate]

This question already has answers here:
Object property name as number
(6 answers)
Closed 3 years ago.
I am working on an API which consists of nested objects with numeric keys. Here is the data:
{ "data": {"0":{"name":"kp"},"1":{"name":"josan"}}
I am wondering how can a key be numeric. As per my knowledge it should not possible.
axios.get(``)
.then( res => {const persons = res.data;
this.setState({persons});
render(){return ({this.state.persons.data."1".name})
I want to access name of 1.
Use bracket notation like so:
this.state.persons.data["1"].name
You can't use numbers usually because all JavaScript object keys are strings - and it gives you a syntax error if you try to use a number in dot notation:
const obj = { 1: "foo" };
console.log(obj..1);
However, because of a quirk of implicit conversion, numbers in bracket notation works fine:
const obj = { 1: "foo" };
console.log(obj[1]);
You can use [] (bracket) notation
var a={ "data": {"0":{"name":"kp"},"1":{"name":"josan"}}}
console.log(a.data[0].name)
console.log(a.data[1].name)
If { "data": {"0":{"name":"kp"},"1":{"name":"josan"}} is the response from the API, and you are already doing this: const persons = res.data;
Then to get the name you need to use this.state.persons['1'].name.

JS destructuring complicated statement? [duplicate]

This question already has answers here:
Javascript object bracket notation ({ Navigation } =) on left side of assign
(5 answers)
What is destructuring assignment and its uses?
(3 answers)
Closed 3 years ago.
let messages = {
1: {
id: '1',
text: 'Hello World',
userId: '1',
},
2: {
id: '2',
text: 'By World',
userId: '2',
},
};
// what does this statement do?
const {
[1]: message,
...otherMessages
} = messages;
console.log("other messages: ", otherMessages);
We didn't have a variable otherMessages, so how does the rest syntax work on this variable? What does the above statement do in general, it's somewhat complicated?
This is a destructuring assignment. See MDN fore more information
On the left side of the = sign, you declare the variables to be destructured, and on the right side the variable to desctructure.
Doing this, you are declaring two variables message and otherMessages:
const { [1]: message, ...otherMessages } = messages;
and you are extracting the value of key 1 into message, and the rest of the messages object will be desctructured into otherMessages.
Since messages contains two entries with keys 1 and 2, otherMessages will be an object containing the remaining keys, which is only key 2.
When trying to assign the variable otherMessages, the runtime checks to see where it is declared. As it goes up the scopes if it reaches the top level, in this case window, it will declare the variable and then assign to it using the destructuring syntax.
Think about this another way: if you were to do something like this:
otherMessages = [1, 2]
Without declaring otherMessages as a var before hand, wouldn’t the runtime declare the variable for you?

javascript three dots syntax [duplicate]

This question already has answers here:
javascript es6 array feature [...data, 0] "spread operator"
(2 answers)
Javascript Property with three dots (...)
(5 answers)
Closed 5 years ago.
I'm using Vuetify for a vue app, in this file I saw a very strange syntax which I can't find what it is
on line 38:
const data = {
attrs: { disabled: this.disabled },
class: this.classes,
props: {},
directives: [{
name: 'ripple',
value: this.ripple || false
}],
on: {
...(this.$listeners || {}), // <<<---- here
click: this.click
}
}
can anyone tell what is that three dots? any articles about this would be nice
thanks
That's the spread operator! It grabs all the properties from the object.
In that example, it'll copy the object without mutating it.
it's a spread operator, which is used in ES6 for both objects and arrays in Javascript. Here, the returned value of (this.$listeners || {}) is extracted. This returned value, combined with click: this.click is added into another empty object, following the "on: "

Variable initiation inside curly braces [duplicate]

This question already has answers here:
Javascript object bracket notation ({ Navigation } =) on left side of assign
(5 answers)
Closed 7 years ago.
What does this code translate to? I can't figure out how the variables inside the curly braces are related to = require('react-router').
var { create: createRouter, HistoryLocation, HashLocation } = require('react-router')
It is from this repo
This is a feature called destructuring assignment in ES6. This is what happens:
// Imagine this is the object you require
var reactRouter = {
create: 'foo',
HistoryLocation: 'bar',
HashLocation: 'baz'
}
// Destructure
var {create: createRouter, HistoryLocation, HashLocation} = reactRouter
// Now the variables are in scope
console.log(createRouter, HistoryLocation, HashLocation)
//^ foo, bar, baz
Looks like it's destructuring assignment. It is a part of Javascript ES6 and is described here.
The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.
Cool new feature! I'm looking forward to using it.

Categories

Resources