Ycon Ycon - 1 month ago 5
React JSX Question

Conditionally send JSON key in fetch

I would like to "conditionally" send a key value.

Basically, the way it currently is it still sends the field

KEY_TEST
regardless of whether or not it contains a value.

I would like to to NOT send the field at all if there is no value. So it will send
{"text":"blah","KEY_TEST":""}
or
{"text":"blah","KEY_TEST":1}


In other words...

IF the there is a value in
this.props.photo.info[0]
, fetch should send:

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


IF the there is not a value in
this.props.photo.info[0]
, fetch should send:

{"text":"blah"}


Here's my full code:

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

Answer

Try like this

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(Object.assign({
            "text": this.state.value.toString('html')
      },keyTest))
      })
      .then(function(res){ return res.json(); })
      .then(function(data){ alert( JSON.stringify( data ) ) })
  },