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?

1

3 Answers 3

2

try this way:

var sortAfter = req.query.sortAfter || '_id';
var ascending = req.query.direction || -1;
var sorted = {};
sorted[sortAfter] = ascending;
Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

1

Use the subscript/bracket notation:

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

The subscript operator will convert its operand to a string,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.