-2

I am using AJAX requests (jQuery) for getting collections of data. Some of the endpoints support extra options for filtering out data (eg api.com/users/?name=chr)

When the data parameter (eg name) is empty, I don't want the request to send it.

I've tried this {name: name !== '' ? name : null} but the request is sending the 'name' parameter as empty string (eg api.com/users/?name=&anotherparam=value)

[EDIT]

Because it got marked as duplicated due to the fact that a possible solution would be to remove empty properties from the data object that is sent, I want to clarify that firstly I wanted to use a feature (parameter omitting) of the framework (in that case jQuery) if that exists, which as I state in my answer, does.

  • How are you sending the request? Assuming it's AJAX and you're providing an object, you can simply remove the empty properties. – Rory McCrossan Dec 21 '18 at 08:30
  • @RoryMcCrossan I know you can do that. You can create and pass the object before the request, but what about when having lots of attributes and want a simpler (and more maintainable) way of doing it? – Chris Athanasiadis Dec 21 '18 at 08:34
  • Having a single function which removes empty properties from any object (see [here](https://stackoverflow.com/a/286162/519413)) is far more simple and maintainable than having to write a ternary for *every single property* - whos names you need to know before runtime. – Rory McCrossan Dec 21 '18 at 08:40
  • @RoryMcCrossan first of all thanks for your time to answer -- forgot to mention that, but it's quite difficult, I guess, to easily distinguish between what's simple or not based on personal preferences, level of knowledge of a specific field, skills, etc. So, yes, maybe the solution you describe is simpler, but for my case (taste, time for refactoring code, etc), I'll go with the approach I describe in my answer! – Chris Athanasiadis Dec 21 '18 at 09:37
  • @RoryMcCrossan also for sure this is not a duplicate of https://stackoverflow.com/questions/286141/remove-blank-attributes-from-an-object-in-javascript as I don't want to explicitly remove attributes from the data object, but rather use a feature of the framework (jQuery) if that exists. – Chris Athanasiadis Dec 21 '18 at 09:49

1 Answers1

0

jQuery when sending a data value as an empty array/object omits it. So this data object {name:name !== '' ? name : []} will omit the parameter name from the request.

  • 2
    just omit the `name` property. Don't send an empty string if you don't require it. – Elish Dec 21 '18 at 08:34
  • @Elish Thanks for your answer, but as I state in my answer (and in the edit of the original question), I wanted to use a feature of the framework if that exists (parameter omitting) – Chris Athanasiadis Dec 21 '18 at 09:58