Alexander Mills
Alexander Mills

Reputation: 100060

Get variable name instead of value

Using bash, I think this is possible, but not sure about JavaScript, say we have this:

    const {masterid} = req.query;

    if (!masterid) {
        return res.status(500).send(new Error('Missing query param "masterid".'));
    }

What I want to do is not hardcode "masterid" in the string, instead do something like this:

    const {masterid} = req.query;

    if (!masterid) {
        return res.status(500).send(new Error(`Missing query param "${Reflect(masterid).name()}.".`));
    }

is there a way to do this with the Reflect API?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect

Upvotes: 0

Views: 3692

Answers (2)

Estus Flask
Estus Flask

Reputation: 222498

This may be possible for testing/debugging purposes but is inappropriate in production. The only way is to tamper it in some way, e.g. parse it, modify and evaluate. For instance, rewire uses eval to intercept top-level module variables, this approach won't work with scoped variables.

Due to these JavaScript limitations, a proper approach is to not rely on variables. There will be no problems with handling property names. Assertions are common in Node, this case can make use of helper function:

assertParam(obj, param) {
  assert.ok(obj[param], `Missing param "${param}".`);
}

...

try {
  assertParam(req.query, 'masterid');
} catch (err) {
  return res.status(500).send(err);
}

Upvotes: 1

Without Haste
Without Haste

Reputation: 642

From this other post

var masterid = 2;
var text = Object.keys({masterid})[0]; //equals "masterid"

Upvotes: 5

Related Questions