1

I am trying to figure out why my node.js application doesn't like it when I try to pass a reference to part of my POST request body as the key of an object literal. Consider the following:

//////////CODE SNIPPET

//problem section of object
"sort": [
    {
        req.body.sortField: {
            "order": req.body.direction,
            "unmapped_type": "boolean"
        }
    }
]

//////////REQUEST BODY

{
    "fromDate": 1468213200000,
    "toDate": 1468219300000,
    "sortField": "#timestamp_milli",
    "direction": "desc",
    "columns": [
        "*"
    ] 
}

I am able to pass the direction property as a value by reference with no issues, but when I try to pass the sort property as a key I get an error when running the application:

req.body.sort: {
   ^
SyntaxError: Unexpected token .

My guess is that I can't pass references as keys in object literals. If this is true, why? Is there a work around for this? If it isn't true, what am I understanding incorrectly here?

Thank you for your time.

EDIT: Clarification between JSON and JavaScript object literals. Also, answered. Thank you everyone!

Joey Marinello
  • 582
  • 3
  • 13

2 Answers2

6

Since ES6 you can have dynamic keys (which is what you seem to be looking for). The syntax for that needs square brackets:

"sort": [
    {
        [req.body.sortField]: {
            "order": req.body.direction,
            "unmapped_type": "boolean"
        }
    }
]

Note that this is not JSON, but a JavaScript object literal.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • That fixed it, and thank you for the clarification between JSON and JavaScript Object Literal. WebStorm tells me "the computed property is not supported" when using the square brackets but it still works. Weird. – Joey Marinello Jul 10 '17 at 21:17
0

Try that

"sort": [
    {
        [req.body.sortField]: {
            "order": req.body.direction,
            "unmapped_type": "boolean"
        }
    }
]

Edit: sorry i miss that part

Arthur
  • 4,870
  • 3
  • 32
  • 57