[英]How do I filter out empty values in an Array?
I am posting to an API, and if no values are entered in the pricing
form fields, I want to send an empty array.我正在发布到 API,如果在pricing
表单字段中没有输入任何值,我想发送一个空数组。
I have tried using the filter method but when I make the post request it sends an array with an empty object ie [{}]
我曾尝试使用 filter 方法,但是当我发出 post 请求时,它会发送一个包含空对象的数组,即[{}]
My state is:我的状态是:
title: "",
ticketing: "", // is equal to 0 (paid) or 1 (free)
pricing: [
{
price: "",
currency: "",
ticketLabel: ""
}
],
When ticketing is equal to 1, no values will be inputted for price
, currency
and ticketLabel
.当 ticketing 等于 1 时,不会输入price
、 currency
和ticketLabel
。
This is my submit function:这是我的提交功能:
handleSubmit = async (event) => {
event.preventDefault();
const info = {
title: this.state.title,
ticketing: this.state.ticketing,
price: [
{
currency: this.state.currency,
price: this.state.price,
label: this.state.ticketLabel
}
].filter(token => Object.keys(token).length != 0)
}
And I post it as我把它发布为
axios
.post(`https://www.diaspora100.com/api/v1/public/events/`, {
info,
})
Currently, this posts as:目前,该帖子为:
price: [{}]
0: {}
I would like it to post as:我希望它发布为:
price: []
Thanks for any help!谢谢你的帮助!
When ticketing is equal to 1, no values will be inputted for price, currency and ticketLabel当ticketing等于1时,不输入价格、货币和票证标签的值
maybe you want something like this也许你想要这样的东西
const info = {
title: this.state.title,
ticketing: this.state.ticketing,
price: this.state.ticketing !== 1 ? [
{
currency: this.state.currency,
price: this.state.price,
label: this.state.ticketLabel
}
] : []
}
在价格的过滤器部分你可以试试这个
<price-array>.filter(token => token.price.length > 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.