19

I need to use a code like this:

vr1 = 'firstName'
value1 = 'Fred'
vr2 = 'lastName'
value2 = 'Flinstone'

axios({
  method: 'post',
  url: '/user/12345',
  data: {
     vr1: Value1,
     vr2: Value2
  }
});

so, it will be the same as executing:

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

Is this possible using Java Script 6?

Jose Cabrera Zuniga
  • 2,348
  • 3
  • 31
  • 56

4 Answers4

15

Try this one also and replace

baseURL
with your own hostname url
import axios from 'axios'

let var1 = 'firstName'
let value1 = 'Fred'
let var2 = 'lastName'
let value2 = 'Flinstone'

const api = axios.create({baseURL: 'http://example.com'})
api.post('/user/12345', {
    var1: value1,
    var2: value2
})
.then(res => {
     console.log(res)
})
.catch(error => {
     console.log(error)
})
Njeru Cyrus
  • 1,753
  • 21
  • 22
12

You can create your own object and pass it to your data request like this:

var obj = {
  [myKey]: value,
}

or 

var obj = {};
obj['name'] = value;
obj['anotherName'] = anotherValue;

Creating object with dynamic keys

Dynamically Add Variable Name Value Pairs to JSON Object

edited: how to post request

const profile = {};
//...fill your object like this for example
profile[key] = value;

axios.post('profile/student', profile)
  .then(res => {
    return res;
  });
Community
  • 1
  • 1
Rafał Schmidt
  • 156
  • 2
  • 6
  • but, how with Axios I could send that object? The docs say nothing about that. At the end the sent data must become JSON for the server to understand – Jose Cabrera Zuniga Apr 18 '17 at 23:59
  • i don't understand where's the problem. I added one more example. I hope that can be useful for you – Rafał Schmidt Apr 19 '17 at 00:08
  • The problem is that the posted tutorials use, instead of an object variable as you did, they used {... } to represent the object and some times it confuses me with programming blocks. Thanks! – Jose Cabrera Zuniga Apr 20 '17 at 18:38
3

Try this it works for me

const obj = {
  firstName: Fred,
  lastName: Flinstone
}
axios
  .post(
    "url",
    this.obj,
  )
  .then(response => {
    console.log(response)
  })
  .catch(error => {
    console.log(error);
  });
John Wanjema
  • 339
  • 1
  • 8
0

To make the keys dynamic, surround them in brackets []

vr1 = 'firstName'
value1 = 'Fred'
vr2 = 'lastName'
value2 = 'Flinstone'

axios({
  method: 'post',
  url: '/user/12345',
  data: {
     [vr1]: Value1,
     [vr2]: Value2
  }
});
thedanotto
  • 6,895
  • 5
  • 45
  • 43