Home > front end >  how to validate key value pair for validation without if-else
how to validate key value pair for validation without if-else

Time:04-26

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.

CodePudding user response:

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();
}

CodePudding user response:

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();
}
  • Related