Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
Set JSON field to undefined if no user input in React - instead of an empty JSON object like "customer": { }

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can try this:

data.customer = Object.keys(data.customer).length ? data.customer : undefined
about 4 years ago · Juan Pablo Isaza Report

0

let name = { d: 'test', };

let data = { name: name.d ? name.d : undefined, email: name.email ? name.email : undefined, };

  1. 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);

about 4 years ago · Juan Pablo Isaza Report

0

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;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!