5

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}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • Also see [Template String As Object Property Name](http://stackoverflow.com/q/33194138/1529630) – Oriol Mar 19 '16 at 00:24

2 Answers2

6

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.

james emanon
  • 11,185
  • 11
  • 56
  • 97
4

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)

iaretiga
  • 5,015
  • 1
  • 13
  • 9