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?
Related
This question already has answers here:
JavaScript get variable in current scope by name
(2 answers)
Closed 1 year ago.
You have a variable:
const test = "Some random value."
and the name of the variable in a string format:
const input = "test"
is there a way to get the value without a enum?
console.log(someMagicFunction(input))
$ => "Some random value."
Thanks!
Short answer - no.
You are kind of describing the behavior of a pointer - sort of... You want to get what is stored in memory and referenced as the variable test. JS does not support that.
There are things you could do such as store the keys and values in a hash map (an object) and have a similar effect.
const store = {
test: "Some random value.",
foo: "bar"
};
const magicHappensHere = (key) => {
return store[key];
};
console.log(magicHappensHere('test')); // "Some random value."
This question already has answers here:
Why can I change a constant object in javascript
(12 answers)
Closed 2 years ago.
Consider the following JavaScript code:
const myObject = {
innerValue: 'test'
}
myObject.innerValue = 'I can still change this, this is not a constant';
If I run this code, the browser outputs no errors, I presume, because only the outer object myObject is a constant and its properties are not. But how valid is this JavaScript code? I mean, are there any negative drawbacks to writing something like this?
Looks like you already understand that the variable myObject is const, but the object to which it refers is not. That's very much by design for JavaScript. Using const the way you did does not protect you from modifying the object.
You could use a property to protect the value of innerValue.
const myObject = {};
Object.defineProperty(myObject, 'innerValue', {
value: 'test',
writable: false
});
console.log(myObject.innerValue);
myObject.innerValue = 'this is not an error but will not change the value';
console.log(myObject.innerValue);
This question already has answers here:
Can I get a javascript object property name that starts with a number?
(2 answers)
How can I access a JavaScript object which has spaces in the object's key?
(4 answers)
Closed 4 years ago.
After fetching a json object from an external API I get the following as an example:
id: 1
name: john
email: something#example.com
3a5411a124378534906a883a0c5ccda5724175eb: USA
So, in JavaScript I can easily access: object.id, object.name, etc.
However, object.3a5411a124378534906a883a0c5ccda5724175eb throws the error:
Identifier directly after number
How do deal with a situation like that? Or, in other words, how can I get the value of USA?
use
object["3a5411a124378534906a883a0c5ccda5724175eb"];
Use the for-in loop on object to access all the properties of objects as follows event the properties like you mention,
var obj = {
id: 1,
name: 'john',
email: 'something#example.com',
'3a5411a124378534906a883a0c5ccda5724175eb': 'USA'
}
for(var prop in obj){
//do the stuff here what you want for each properties
console.log(obj[prop]);
}
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"
}
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.