-1

I want to set object like this:

var x = 20;
var y = 30;
var z = {
         values: { 
                  x: '24',
                  y: '60'  }, 
         value: x
         };

I would like the variable z to look:

var z = {
         values: { 
                  20: '24',
                  30: '60'  }, 
         value: 20
         };
Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73
  • Possible duplicate of [What do square brackets around a property name in an object literal mean?](https://stackoverflow.com/questions/34831262/what-do-square-brackets-around-a-property-name-in-an-object-literal-mean) – Joe Clay Feb 27 '18 at 16:08
  • Numbers are not valid variable names and cannot be used. [More Info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types) – John Pavek Feb 27 '18 at 16:10
  • Possible duplicate of [How to create an object property from a variable value in JavaScript?](https://stackoverflow.com/questions/2241875/how-to-create-an-object-property-from-a-variable-value-in-javascript) – Ron van der Heijden Feb 27 '18 at 16:10

2 Answers2

7

Put them in square bracket. This is commonly known as computed property names which allows a variable to put in square bracket which will be computed

var x = 20;
var y = 30;
var z = {
  values: {
    [x]: '24',
    [y]: '60'
  },
  value: x
};

console.log(z)
brk
  • 48,835
  • 10
  • 56
  • 78
1

Square bracket solution posted by brk is good, but only under browsers different than Internet Explorer. Under IE11 you need to do something like this:

var x = 20;
var y = 30;
var z = {
         values: { }, 
         value: x
        };

z['values'][String(x)] = '24';
z['values'][String(y)] = '60';

console.log(z);
TomAsh
  • 30
  • 5