0

I want to send the following JSON to the server:

{"active": "true"}

and I try to do it like this:

 axios.patch('/api/musician/' + id, { key : val }).then(function (response) {

The variables key and val contain what I want:

console.log(key);    // active
console.log(val);    // true

However, what gets sent is:

{key: true}

I can't see why the value of variable "key" isn't used. Why is it not sending {"active": "true"} or {"active": true}?

trajekolus
  • 535
  • 6
  • 16
  • 3
    because `{ key : val }` notation, key is literally the string "key" ... new school JS, you can do `{ [key] : val }` - if that doesn't work ... [look at transpier output](http://babeljs.io/repl/#?babili=false&browsers=&build=&builtIns=false&code_lz=IYDwlg9gzgdADsALgYwBYAoDkB6YczYC2ArlGMmMAHbaYAEA1HWACYA0dA3nQNoDWAUwCeAXToAuOgDdgAGzoBfAJRA&debug=false&circleciRepo=&evaluate=true&lineWrap=false&presets=es2015&targets=&version=6.26.0) – Jaromanda X Nov 03 '17 at 04:03

1 Answers1

2

This is because {key: value} is an object literal. You're defining the key as literally "key", and the value as the dynamic value.

To get what you want you can do as Jaromanda X says above:

{ [key] : val }

This should work in modern JS.

If you don't have the latest fanciness, move that object's construction out of that function call:

var data = {}
data[key] = value

This will let you use the variable key as a name.

Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261