Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new object with variable key and value on one line [duplicate]

Tags:

javascript

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}
like image 623
ThomasReggi Avatar asked Mar 19 '16 00:03

ThomasReggi


2 Answers

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.

like image 69
james emanon Avatar answered Sep 30 '22 11:09

james emanon


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)

like image 45
iaretiga Avatar answered Sep 30 '22 12:09

iaretiga