0

I wonder how I can add items to my data object.

This is how I make a post request using axios:

axios({
    method: 'post',
    url: 'someUrl',
    responseType: 'json',
    data: {
        title: titleData
    }
})

But sometimes I need to add more items to the data object depending on how many fields the user has filled.

So sometimes the request data might look like this:

axios({
    method: 'post',
    url: 'someUrl',
    responseType: 'json',
    data: {
        title: titleData,
        location: locationData,
        isReady: readyData
    }
})

So how can I push items to the data: {} object?

csblo
  • 1,571
  • 13
  • 20
Kiow
  • 870
  • 4
  • 18
  • 32

3 Answers3

2

With axios, the field data must contain an object, so :

var data = { title:titleData };

if (mySpecialCase)
{
    data["location"] = locationData;
    data["isReady"] = isReady;
}

axios({
    method: 'post',
    url: 'someUrl',
    responseType: 'json',
    data: data
})
csblo
  • 1,571
  • 13
  • 20
0

You could keep the object in a variable, then pass on request:

var data={};
//then assign
data.title="test";
//or multiple at once
Object.assign(data, {
        location: locationData,
        isReady: readyData
});
//then do the request
axios({
      method: 'post',
      url: 'someUrl',
      responseType: 'json',
      data
    })
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

Can't you add property directly by their name

data['newPropertyName'] = value

or

data.newPropertyName = value

Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41