I am trying to post a JSON object to an API with 2 fields. However if these fields are empty (ie no values were inputted on the form) I want to send an empty array.
The section of the form allows for 2 ticketing options: paid and free, if free is selected no values will be inputted into these 2 fields.
This is what the pricing
and ticketing
option looks like in my state:
ticketing: "" // this would be either 0 or 1
pricing: [
{
price: "",
currency: "",
}
],
And this is how I send it to my API:
const info = {
ticketing: this.state.ticketing,
price: [
{
currency: this.state.currency,
price: this.state.price,
}
],
}
axios
.post(`https://www.somewhere.com`, {
info
})
When no values are inputted for price
and currency
the form posts:
price: [{}]
0: {}
I would like it to post:
price: []
instead, please let me know how I can do this.
I have updated my answer to show that the API receives the the data in single constant.
Thanks for any help!
You may filter out empty objects from price
array using filter()
. Here is a sample:
prices = { price: [ { currency: "USD", price: 5.0, }, {} ].filter(token => Object.keys(token).length != 0) } console.log(prices);
If you want this filter to only work when currency
and price
, you can remove any element not having both by using the filter
method :
axios.post(`https://www.somewhere.com`, {
info: info.filter(inf => inf.currency && inf.price)
})
If you want your info
to work with any kind of object by keeping object that have any of their values defined, you can use the some
method on their values :
axios.post(`https://www.somewhere.com`, {
info: info.filter(inf => Object.values(inf).some(i => i))
})
const {currency, price} = this.state; const pricing = {price: []} if(currency && price) pricing.price.push({currency, price}) axios.post(`https://www.somewhere.com`, { pricing })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.