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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With