Reputation: 3832
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?
Upvotes: 0
Views: 53
Reputation: 1188
try this way:
var sortAfter = req.query.sortAfter || '_id';
var ascending = req.query.direction || -1;
var sorted = {};
sorted[sortAfter] = ascending;
Upvotes: 2
Reputation: 17094
Use the subscript/bracket notation:
var sorted = {};
sorted[sortAfter] = ascending;
The subscript operator will convert its operand to a string,
Upvotes: 1
Reputation: 522500
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;
Upvotes: 1