Reputation: 1147
For a certain axios request:
API.post(
`v${process.env.REACT_APP_API_VERSION}/register/company/`,
{
type: values.type,
dba: values.dba,
ein: values.ein,
file_type: values.file_type,
},
I'd like to avoid sending parameters if they're not assigned a value (are still "").
i.e. I would like to know the cleanest way of only including non-empty parameters in my request object. I can do this using an if check but doing so for every item on larger requests wouldn't make sense. for example:
const postData = {
first_name: values.first_name,
last_name: values.last_name
};
if (values.middle_name !== "") {
postData.middle_name = values.middle_name;
}
Thanks
Upvotes: 2
Views: 1506
Reputation: 608
You can try something like this:
Object.keys(values).forEach((key) => {
if(!values[key]) delete values[key];
})
What it basically does is it deletes any element inside the values
object that is falsey, which includes empty strings.
Upvotes: 3
Reputation: 14464
Shortest solution I can think of. For general solution I'd use a wrapper, but if you need to check only few of properties, this one can be enough.
const v = values;
API.post(
`v${process.env.REACT_APP_API_VERSION}/register/company/`,
{
...(v.type&&{type: v.type}),
...(v.dba&&{dba: v.dba}),
...(v.ein&&{type: v.ein}),
file_type: values.file_type,
},
Upvotes: 0