在 fetch 中有条件地发送 JSON 键

Conditionally send JSON key in fetch

我想"conditionally"发送一个键值。

基本上,目前的方式仍然发送字段 KEY_TEST,无论它是否包含值。

如果没有值,我想完全不发送该字段。所以它会发送 {"text":"blah","KEY_TEST":""}{"text":"blah","KEY_TEST":1}

换句话说...

如果 this.props.photo.info[0] 中的一个值,提取应该发送:

{"text":"blah","KEY_TEST":1}

如果在 this.props.photo.info[0] 没有 值,提取应该发送:

{"text":"blah"}

这是我的完整代码:

editorUpdate: function(e) {
    e.preventDefault();
     return fetch(URL {
     method: 'PUT',
     body: JSON.stringify({
     "info": [{
            "text": this.state.value.toString('html'),
            "KEY_TEST": this.props.photo && this.props.photo.info && this.props.photo.info[0] && this.props.photo.info[0].pk || '',
      }]
      })
      })
      .then(function(res){ return res.json(); })
      .then(function(data){ alert( JSON.stringify( data ) ) })
  },

这样试试

editorUpdate: function(e) {
     e.preventDefault();
     var keyTest = (this.props.photo && this.props.photo.info && this.props.photo.info[0]) ? {"KEY_TEST": this.props.photo.info[0].pk} : {}; 
     return fetch(URL {
     method: 'PUT',
     body: JSON.stringify({ info : [ Object.assign({
            "text": this.state.value.toString('html')
      },keyTest)]})
      })
      .then(function(res){ return res.json(); })
      .then(function(data){ alert( JSON.stringify( data ) ) })
  },