【问题标题】:Posting an Empty Array to an API if JSON object is empty如果 JSON 对象为空,则将空数组发布到 API
【发布时间】:2019-08-20 09:52:21
【问题描述】:

我正在尝试将 JSON 对象发布到具有 2 个字段的 API。但是,如果这些字段为空(即表单上没有输入值),我想发送一个空数组。

表单部分允许 2 个票务选项:付费和免费,如果选择免费,则不会在这 2 个字段中输入任何值。

这是pricingticketing 选项在我的状态下的样子:

ticketing: ""       // this would be either 0 or 1
pricing: [
              {
                price: "",
                currency: "",
              }
            ],

这就是我将它发送到我的 API 的方式:

const info = {
  ticketing: this.state.ticketing,
  price: [
              {
                currency: this.state.currency,
                price: this.state.price,
              }
            ],
  }

axios
     .post(`https://www.somewhere.com`, {
       info
     })

当没有为pricecurrency 输入值时,表单帖子:

price: [{}]
  0: {}

我想发布:

price: []

相反,请告诉我如何做到这一点。

我已更新我的答案以表明 API 接收单个常量中的数据。

感谢您的帮助!

【问题讨论】:

  • 因为你传入数组的对象,当字符串为空时,你会在数组中得到一个空对象。如果字符串存在,您可以简单地添加添加对象的逻辑,如果不存在则只添加一个空数组。
  • 我会选择let pricing = ...而不是const,然后在post之前使用pricing.price = pricing.price.filter(p => Object.entries(p).length !== 0)
  • @WillAlexander 我已经更新了我的答案以表明 API 接收单个常量中的数据。

标签: javascript arrays json reactjs post


【解决方案1】:

您可以使用filter()price 数组中过滤出空对象。 这是一个示例:

prices = {
    price: [
        {
            currency: "USD",
            price: 5.0,
        }, {}
    ].filter(token => Object.keys(token).length != 0)
}
console.log(prices);

【讨论】:

  • 我已更新我的答案以表明 API 接收单个常量中的数据。
  • 添加后我没有看到任何区别。它仍然在数组中发布一个空对象,不过感谢您的回复
  • 我已经展示了如何从数组中删除/过滤空对象。这需要添加到您的代码中,其中所有您都有一个数组,其中可能包含空对象。您的代码示例不完整,因此我无法准确指出您必须在哪里应用它。方向是:形成数组,应用过滤器,添加到请求结构并发送到后端 API。
【解决方案2】:

如果您希望此过滤器仅在 currencyprice 时起作用,您可以使用 filter 方法删除任何不同时具有这两者的元素:

axios.post(`https://www.somewhere.com`, {
  info: info.filter(inf => inf.currency && inf.price)
})

如果您希望 info 通过保留定义了任何值的对象来处理任何类型的对象,您可以对它们的值使用 some 方法:

axios.post(`https://www.somewhere.com`, {
  info: info.filter(inf => Object.values(inf).some(i => i))
})

【讨论】:

    【解决方案3】:

    const {currency, price} = this.state;
    const pricing = {price: []}
    if(currency && price) pricing.price.push({currency, price})
    
    axios.post(`https://www.somewhere.com`, { pricing })

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多