4

I'm trying to request some data from the server. When I change a property's model to undefined this "undefined" string is sent in the query string.

let filterModel = new GroupFilterModel();
filterModel.status = anycondition ? "opened" : undefined;
this.http.get<GroupModel[]>("apiurl", { params: filterModel });

The querystring sent is something like this:

apiurl?status=undefined

I want to avoid sending the status variable. How can I have this behaviour?

Gabriel Castillo Prada
  • 4,114
  • 4
  • 21
  • 31

2 Answers2

3

Use this one liner in ES6:

Object.keys(obj).forEach(key => obj[key] === undefined ? delete obj[key] : '');

As if:

filterModel.status = anycondition ? "opened" : undefined;
const model = Object.keys(filterModel).forEach(key => obj[key] === undefined ? delete obj[key] : '');
this.http.get<GroupModel[]>("apiurl", { params: model });

You can go even further and make it an extension on the object:

Object.prototype.StripUndefined = function StripUndefined() {
  return this.keys(filterModel).forEach(key => obj[key] === undefined ? delete obj[key] : '');
};
Yaser
  • 5,609
  • 1
  • 15
  • 27
1

You can remove properties that have undefined and null values with lodash as follows:

let filterModel = new GroupFilterModel();
filterModel.status = anycondition ? "opened" : undefined;
this.http.get<GroupModel[]>("apiurl", { params: _.pickBy(filterModel) });

For other solutions using vanilla JS see:

Remove blank attributes from an Object in Javascript

danday74
  • 52,471
  • 49
  • 232
  • 283