Reputation: 2637
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?
Upvotes: 21
Views: 93848
Reputation: 7327
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
}
});
Upvotes: 0
Reputation: 354
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);
});
Upvotes: 3
Reputation: 1789
Try this one also and replace
baseURLwith 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)
})
Upvotes: 16
Reputation: 156
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;
});
Upvotes: 12