Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
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 Respostas
Responde à pergunta

0

You can try this:

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

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda