DonLeo DonLeo - 5 months ago 51
TypeScript Question

Angular2 how to hide empty array in POST

In my filters I have products list. I want to send this array only, when there are some elements. Is it possible?

Request function:

getRecipes(page, pageSize, filters){
let body = JSON.stringify({ "size": pageSize, "page": page, "listOfFilters": filters});
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });

.map((res: Response) => res.json());}

Filter Class:

export class Filter{
products = new Array<String>();
rating: {[key: string]:string} = {};
level: {[key: string]:string} = {};

Now JSON looks like:


And I want it to looks like (when products list is empty):



I'm not entirely sure, how you want the endresult to look like, but this is a simple if condition, where you can leverage delete.

if (filters.products.length == 0) {
    delete filters.products;

let body = JSON.stringify({ "size": pageSize, "page": page, "listOfFilters": filters });