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

142
Visualizações
how to validate key value pair for validation without if-else

I am checking if the object value is empty string and if the value is empty then i am setting the state variable warning value for that same key true

const PrimaryEntryDetails = {
    name: "Pinak",
    number: 79777777,
    address: ""
}

const [warning,setWarning] = useState({
    name: false,
    number: false,
    address: false
})

 Object.keys(PrimaryEntryDetails).map((key) => {
     if(PrimaryEntryDetails[key] === ""){
         setWarning({...warning, [key] : !PrimaryEntryDetails[key]})
     }
  })

if the value of PrimaryEntryDetails key is empty then I am updating the warning state variable but it's not working properly.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I think using a list of property names is more maintainable:

const propertyNames = [
  'productName',
  'productMaker',
  'model',
  'productDescription',
  'datePurchase',
  'productPrice',
];

const missingProperty = propertyNames.find(name => PrimaryEntryDetails[name] === '');

if (missingProperty) {
  setWarning({...warning, [missingProperty]: true});
}
else {
  setWarning(WarningProp);
  onContinue();
}

about 4 years ago · Juan Pablo Isaza Relatório

0

Assuming the format

const PrimaryEntryDetails =  {
  "productName": "Name of product",
  ....

You could use .entries without the need to know or update a list of names

NOTE: This version will warn on ALL missing values and not just stop at the first

let warnings = 0;
Object.entries(PrimaryEntryDetails).forEach(([key, value]) => {
  if (value.trim() === "") {
    setWarning({ ...warning,
      [key]: true
    })
    warnings++;
  }
})
if (warnings === 0) { // assuming the code in your example worked
  setWarning(WarningProp);
  onContinue();
}

If you want to warn on the first empty one, use find

let warnings = 0;
const entry = Object.entries(PrimaryEntryDetails).find(([key, value]) => value.trim() === "")
if (entry) setWarning({ ...warning, [entry[[0]]: true })
else {
  setWarning(WarningProp);
  onContinue();
}
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