Help

Re: JSON reading as literal rather than variable

Solved
Jump to Solution
2245 2
cancel
Showing results for 
Search instead for 
Did you mean: 
Bryn_Humble
5 - Automation Enthusiast
5 - Automation Enthusiast

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?

1 Solution

Accepted Solutions
openside
10 - Mercury
10 - Mercury

@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 }

See Solution in Thread

4 Replies 4

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.

openside
10 - Mercury
10 - Mercury

@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 }

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. :slightly_smiling_face:

Thank you, this solved the issue.