This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 6 years ago.
I'm looking for a simple syntax to allow me to create a new object with one property and set the value of that property. Here's an example. I'd love to be able to do something all on one line.
let parent = 'jackets',
let responses = [{'color':'red', 'size':'medium'}]
let tmp = {}
tmp[parent] = responses
return tmp
Should log:
{
"jackets": [
{
'color':'red',
'size':'medium'
}
]
}
I thought I saw once that this was going to be possible in the es-spec but it doesn't work with the babel-2015 preset.
let jackets = {`${parent}`: responses}
this works for me:
*note: I have the result consoling to the console. Open console to see the results.
const responses = [{'color':'red', 'size':'medium'}]
const jackets = "jackets"
const A = {[jackets]: responses}
console.log(A)
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.1.19/browser.min.js"></script>
0Aconst%20A%20%3D%20%7B%5BL%5D%3A%20responses%7D%0Aconsole.log(A)%0A
const jackets = {[parent]: responses}
console.log(jackets)
// gives
{"jackets":[{"color":"red","size":"medium"}]}
noted: other person got in before me.
You will need to use computed property names.
const key = 'foo';
const value = 'bar';
const foobar = {[key]: value}; // {foo: 'bar'}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names
(This works with es2015 Babel preset)
Related
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 4 months ago.
const A = 0;
const LOOKUP = { A : "A"};
console.log(LOOKUP[A]);
console.log(LOOKUP[0]);
Result:
undefined
undefined
Second try:
var A = 0;
const LOOKUP = { A : "A"};
console.log(LOOKUP[A]);
console.log(LOOKUP[0]);
Result:
undefined
undefined
How am I supposed to do this then? And can somebody explain why this doesn't work in JavaScript the way one would expect it to work coming from other languages?
The correct way is:
const A = 0;
const LOOKUP = {};
LOOKUP[A] = 'A';
console.log(LOOKUP[A]);
console.log(LOOKUP[0]);
const LOOKUP = { A : "A"};
The left side of the colon means that the key is the string "A". The string part is implicit, since all keys are strings (or symbols). So to access the property, you need to do console.log(LOOKUP.A) or console.log(LOOKUP["A"])
If you want the key to be a computed value, then you need to use square brackets:
const LOOKUP = { [A]: "A" };
That means that we should resolve the variable A, and use its value as the key. That key is the number 0, which then gets coerced into the string "0". You can then look it up by any of console.log(LOOKUP["0"]), console.log(LOOKUP[0]), or console.log(LOOKUP[A])
Looks like you are searching for some enums (typescript):
enum ETest {
A = 1
};
console.log(ETest['A']); // 1
console.log(ETest[1]); // A
Doing LOOKUP[A] is like doing LOOKUP[0] which is undefined.
You should try it as
console.log(LOOKUP["A"])
This has nothing to do with const or var keyword. The way you are trying to access an object property is incorrect.
const A = 0;
const LOOKUP = { A : "A"};
console.log(LOOKUP["A"]); // Correct Approach: Property access through bracket notation should be done using a string (or a variable assigned to a string).
console.log(LOOKUP[0]); // Property `0` doesn't exist on object `LOOKUP`, so it'll return `undefined`.
This question already has answers here:
Javascript object bracket notation ({ Navigation } =) on left side of assign
(5 answers)
Closed 4 years ago.
I'm new in react and I'm reading some code i found this line of code:
const {intl: { formatMessage }, } = this.context
is a const declaration but i don't understand
I know is JS ES6 but i don't understand what is it for?
How can I check the value of this const?
thanks
As people already answered. This is object destructuring
Simple example: const contact = {name: 'John', email: 'john#doe.com'}
With ES6 you can do const {email} = contact; //email = contact.email
In case you want to name the variable differently, it would be:
const {email: mailbox} = contact //equivalent to mailbox = contact.email;
Back to the original question: {intl: { formatMessage }, } = this.context
=> {formatMessage} = this.context.intl => formatMessage = this.context.intl.formatMessage
The code that you have is, actually a representation of the following code,
const formatMessage = this.context.intl.formatMessage
You can read about object destructuring to know more about it.
This simply means that this.context contains a structure similar to this
this.context = {
intl:{
formatMessage: // This has a value let's say "Hello"
},
//Other key-value pairs could be contained in the context object }
This line of code is a shorthand syntax telling you that only the formatMessage property which can be found inside "intl" should be retrieved from the large object called "this.context"
This question already has answers here:
Javascript object bracket notation ({ Navigation } =) on left side of assign
(5 answers)
Syntax: const {} = variableName, can anyone explain or point me into the right direction [duplicate]
(1 answer)
Closed 4 years ago.
On this page (https://nodejs.org/api/modules.html), I found this writing: { }.
const { PI } = Math;
Does it have a particular name, so that I can get more information about it, and especially what does it produce?
Thanks in advance. :D
This is called "destructuring assignment". You can think of it as being equivalent to:
const PI = Math.PI;
…but a little more compact. It really shines when being used to pluck multiple properties off an object:
const { foo, bar, baz } = require('quux').util;
You can also destructure arrays using [ ]:
const [ first, second, third ] = array;
The curly brackets in javascript typically represent an object, but in this case, it is a "destructuring assignment". For example:
const obj = { value: 'hello world' };
const {value} = obj;
console.log(value); // outputs: hello world
As object keys are strings they can contain any kind of characters and special characters. I recently stumbled upon an object which I receive from an API call. This object has '-' in it's key names.
const object = {
"key-with-dash": []
}
Destructuring does not work in this case because key-with-dash is not a valid variable name.
const { key-with-dash } = object;
So one question came to my mind. How am I supposed to destructure the object in such cases? Is it even possible at all?
const data = {
"key-with-dash": ["BAZ"]
}
const {"key-with-dash": foo} = data;
console.log("foo", foo);
Just give it a valid name
let object = { 'key-with-dash': [] }
let {'key-with-dash':y} = object
console.log(y)
// => []
Did you also know you can destructure with variables?
let object = { 'key-with-dash': [] }
let key = 'key-with-dash'
let {[key]:y} = object
console.log(y)
// => []
Hello Fellow Developers,
I have found a break through this error if none of the above work.
Follow this code
<i>const anyVar = yourData["data-example"] </i>
Hope this works for you if you have any questions please make to ask me.
P.S: I know its a old question but I faced a issue so I thought that some people may also face this. So that is why I have posted this.
This question already has answers here:
Get the description of a ES6 Symbol
(4 answers)
Closed 5 years ago.
Suppose I have a symbol such as const sym = Symbol('foo');. Now, is there a way to get the value foo from that symbol without relying on string manipulations?
I expected sym.toString() to return 'foo' but it returns Symbol(foo).
Update
I settled with this hacky solution, until I find a better one :)
const key = Symbol.keyFor(sym) || (sym = sym.toString(), sym.substring(7, sym.length - 1));
There is the Symbol.keyFor. But it only works with the globally registered symbols
const works = Symbol.for('foo');
const key1 = Symbol.keyFor(works); // "foo"
const doesNotWork = Symbol('foo');
const key2 = Symbol.keyFor(doesNotWork); // undefined
I'm guessing that the private symbols do this by design. You could always monkey patch it:
const patched = Symbol('foo');
patched.key = 'foo';