Ilja
Ilja

Reputation: 46509

Conditionally include json field inside return statement

So, I came across an issue, I'm usually returning empty strings if I can't find a value or if it is undefined. Like so:

return {
  _method: 'update',
  link: get(media, 'link', ''),
  caption: get(media, 'caption', '')
};

where get() is a lodash function that simply returns something (in this case empty string) if it can't find value within a provided path.

however I now need to return nothing if the field is not there, I tried

return {
  _method: 'update',
  get(media, 'link', '') ? link: media.link : '',
  get(media, 'caption', '') ? link: media.caption : '',
};

but that is not a valid syntax.

Upvotes: 0

Views: 92

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167192

If you cannot have that field, then don't do object creation on the fly. Use something like:

obj = {};
// add static values here.
obj["_method"] = 'update';

// dynamic now
if (get(media, 'link', ''))
  obj["link"] = media.link;
if (get(media, 'caption', ''))
  obj["caption"] = media.caption;

// And finally return the obj.
return obj;

That's the best way I could think of.

Upvotes: 1

Related Questions