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

133
Views
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 answers
Answer question

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 Report

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 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!