1

I'm trying to set up an object using a variable. Here's what I have:

var sortby = 'post_date';
var sort = { sortby : 'asc' };

but when I console.log(sort) I get Object {sortby: "asc"}

How can I set the key of this object to the value of a variable?

psorensen
  • 809
  • 4
  • 17
  • 33

2 Answers2

2

Object literals can't have dynamic property names, but property setter syntax works:

var sortby = 'post_date';
var sort = { };
sort[sortby] = 'asc';
Douglas
  • 36,802
  • 9
  • 76
  • 89
2

Prior to ES6 (the newest JavaScript standard), you could only do the following:

var sortby = 'post_date';
var sort = {};

sort[sortby] = 'asc';

However, if you made sure that you can use ES6 features for what you're doing, this is also possible:

var sortby = 'post_date';

var sort = {
  [sortby]: 'asc
};

See this pages for more information on ES6 features: https://github.com/lukehoban/es6features

reg4in
  • 564
  • 3
  • 9