JSON reading as literal rather than variable

I am having an issue updating a record using the API where the update method is treating a variable as a literal value, rather than the value it contains.

My code is:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

var Airtable = require('airtable');
var base = new Airtable({apiKey: 'censored'}).base('appYYigSAYG6wvbIL');


app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.post('/update',function(req,res){
  var exam=req.body.exam;
  var status=req.body.status;
  console.log(status);
  console.log(exam);
  res.end("yes");
  base('Staff').update("recL2tsSb73D8NdVj", {
  exam : status
}, function(err, record) {
  if (err) {
    console.error(err);
    return;
  }
  console.log(record.get('Name'));
});
});

app.get('/', function (req, res) {
   res.send('atapi is up');
})

var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port
   
   console.log("Example app listening at http://%s:%s", host, port)
})

The status is read as its value (ie Pass), but exam is read as the literal word exam, causing it to fail due to that field name not existing. Can anyone point out where I am going wrong?

I’m just now digging back into JavaScript after a really long hiatus, but from what I understand about objects, you can’t use a variable as a name in a name:value pair. exam in the context of exam : status will always be treated as exam, not as the value you assigned to the variable exam earlier in the code. To do what you want, where the code updates a field based on the variable exam, will require a condition, probably switch because it’s more efficient.

@Justin_Barrett is on the right track. To use the vale of the variable in your object key, just need to enclose with brackets. So
{ [exam]: status }

2 Likes

I figured there had to be a way to still use the variable, but haven’t come to that yet in my JavaScript refresher review. :slight_smile:

Thank you, this solved the issue.