I have a JSON variable data that has a customer field with 6 properties:
const submit = async (values) => {
const data = {
customer: {
firstname: values.firstname,
lastname: values.lastname
...
},
...
...
And a form in which user inputs are submitted to the JSON variable:
<Field name="firstname" component={InputField} type="text" />
<Field name="lastname" component={InputField} type="text" />
These fields are not required but the empty customer object still gets sent to my API as "customer": { }
How can I get rid of it? I know if I set the customer object to undefined, it will be ignored from the whole JSON, but can't seem to figure out where I should set it so that it does not look bad.
I guess it is something like this?
data.keys(customer).length > 1 ? customer : undefined
Q: is there any way to check inside the const variable, that values contain customer data, and if not, it defaults to undefined?
CodePudding user response:
By using delete keyword you can delete the customer property if it is empty, now your data will have all the properties without the customer property
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
if('customer' in data)
{
if(isEmpty(data.customer))
delete data.customer;
}
CodePudding user response:
You can try this:
data.customer = Object.keys(data.customer).length ? data.customer : undefined
CodePudding user response:
let name = { d: 'test', };
let data = { name: name.d ? name.d : undefined, email: name.email ? name.email : undefined, };
- List item
let name = {
d: 'test',
};
let data = {
name: name.d ? name.d : undefined,
email: name.email ? name.email : undefined,
};
console.log('data===>', data);
console.log('data===>', data);