Anders Östman
Anders Östman

Reputation: 3832

Creating objects with variable properties

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

Answers (3)

Lifecube
Lifecube

Reputation: 1188

try this way:

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

Upvotes: 2

c.P.u1
c.P.u1

Reputation: 17094

Use the subscript/bracket notation:

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

The subscript operator will convert its operand to a string,

Upvotes: 1

deceze
deceze

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

Related Questions