I would like to validate data using map.I would like to get the key name and check some conditions
const obj = {
firstName: ['errorFirstName', 'msgFirstName'],
lastName: ['errorLastName', 'msgLastName'],
middleName: ['errorMiddleName', 'msgMiddleName'],
}
if (Object.keys(obj).includes(field)) {
//I would like to pass here the object key length for each key :example if(this.firstName.length === 0)
if(this[obj[key]].length === 0) {
const [hasError, msg] = obj[field];
this[hasError] = true;
this[msg] = `${field} is required.`;
}
}
CodePudding user response:
Simply use the key field
to retrieve the value from your object:
const obj = {
firstName: ['errorFirstName', 'msgFirstName'],
lastName: ['errorLastName', 'msgLastName'],
middleName: ['errorMiddleName', 'msgMiddleName'],
}
Object.keys(obj).forEach(fieldName => {
if (this[fieldName].length === 0) {
// your logic here
const [hasError, msg] = obj[fieldName];
this[hasError] = true;
this[msg] = `${fieldName} is required.`;
}
}