0

User table has a column called "name" and req.body.key = name. I don't want to write name = req.body.value. How do i somehow interpolate req.body.key? "{req.body.key}" doesn't work and console throws User.{req.body.key} does not exist.

function(req, res, next) {
    User.findAll({
        where: {
            //Question HERE
            req.body.key : req.body.value           
        }
    }).then(...).catch(...)
}
Yi Lu
  • 163
  • 1
  • 6
  • this solves it: http://stackoverflow.com/questions/5640988/how-do-i-interpolate-a-variable-as-a-key-in-a-javascript-object – Yi Lu Jun 08 '16 at 17:12
  • What about the answer below? It has the advantage of showing ES6 too. – rels Jul 05 '16 at 14:02

1 Answers1

1

Try this:

function(req, res, next) {
    var whereClause = {};
    whereClause[req.body.key] = req.body.value;
    extend(whereClause, req.body);
    User.findAll({
        where: whereClause
    }).then(...).catch(...)
}

In ES6 (node > 5-6 I don't remember) you can also:

function(req, res, next) {
    extend(whereClause, req.body);
    User.findAll({
        [req.body.key]: eq.body.value
    }).then(...).catch(...)
}
rels
  • 715
  • 2
  • 7
  • 22