I have a search form with several fields. If user types nothing into field, it still will be sent to the server with value "null".
However, there are about 25 optional (advanced) fields in this form, and if user types nothing into it, JSON shouldn't contain this field at all.
So, my question is: is there some way (pattern maybe) to avoid those 25 "if () else"? What is the best way to form that final JSON?
Thanks!
UPD: Thank you, @RIYAJKHAN for your answer! I've managed to solve it by myself using LoDash:
private compactObject(obj) {
let compactObj = this.removeEmptyProperties(_.cloneDeep(obj));
_.forEach(compactObj, (value, key) => {
if (_.isObject(value)) {
compactObj[key] = this.compactObject(this.removeEmptyProperties(compactObj[key]));
}
});
return this.removeEmptyProperties(compactObj);
};
private removeEmptyProperties(obj) {
let trimedObj = _.cloneDeep(obj);
_.forEach(trimedObj, (value, key) => {
if (!value || _.isEmpty(trimedObj[key])) {
delete trimedObj[key];
}
});
return trimedObj;
}