有条件地在fetch中发送JSON密钥

时间:2016-11-03 06:26:40

标签: json reactjs fetch

我想"有条件地"发送密钥值。

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

如果没有价值,我想不要发送字段。因此,它会发送{"text":"blah","KEY_TEST":""}{"text":"blah","KEY_TEST":1}

换句话说......

如果 this.props.photo.info[0]中的值,则fetch应发送:

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

如果this.props.photo.info[0]中有值,则应提取fetch:

{"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 ) ) })
  },

1 个答案:

答案 0 :(得分:1)

试试这个

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 ) ) })
  },