Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

147
Vistas
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 Respuestas
Responde la pregunta

0

You can try this:

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

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda