0

I'm trying to do this:

var sortAfter = req.query.sortAfter || '_id';
var ascending = req.query.direction || -1;
var sorted = {sortAfter: ascending};

But a console.log(sorted) output the following object:

{ sortAfter: -1 }

It's like the first variable is not used in the object creation...

Question: How do i get the object to be made of two variables, and not one variable and one fixed string?

Anders Östman
  • 3,702
  • 4
  • 26
  • 48
  • possible duplicate of [Passing in dynamic key:value pairs to an object literal?](http://stackoverflow.com/questions/4119324/passing-in-dynamic-keyvalue-pairs-to-an-object-literal) – Felix Kling Oct 23 '13 at 08:22

3 Answers3

2

try this way:

var sortAfter = req.query.sortAfter || '_id';
var ascending = req.query.direction || -1;
var sorted = {};
sorted[sortAfter] = ascending;
Lifecube
  • 1,198
  • 8
  • 11
1

In object literals, the keys are always literals, they're never variables. If you want to set a dynamic object key, you'll have to do it like this:

var sorted = {};
sorted[sortAfter] = ascending;
deceze
  • 510,633
  • 85
  • 743
  • 889
1

Use the subscript/bracket notation:

var sorted = {};
sorted[sortAfter] = ascending;

The subscript operator will convert its operand to a string,

c.P.u1
  • 16,664
  • 6
  • 46
  • 41