1

Using a variable for a key in a JavaScript object literal

I am started learning javascript and have seen the answer(below) for the above question but

var thetop = "top",
obj = { [thetop]: 10 };                                 
console.log(obj.top); 

what if i have

var date = new Date().getDate(); 
var value= String(date); 
obj ={[value]:100};
console.log(obj.value);

I did not find the answer for the above code .As the variable value changes everyday i want to use value while using console.log(obj.value) not the actual date. Can someone tell me how to do it .

Belmin Bedak
  • 9,011
  • 2
  • 40
  • 44
nuy5
  • 27
  • 1
  • 8

1 Answers1

0

You can read the value property with "[]" instead of ".", like this:

var date = new Date().getDate(); 
var value= String(date); 
obj ={[value]:100};
console.log(obj[value]);
Nima Hakimi
  • 1,382
  • 1
  • 8
  • 23