I am encountering an issue with validating an array of objects, specifically a table with rows where each row represents an object. The problem is that no error message appears if there is an error in the middle row of the table. However, if there's an error in the last row, it does show an error message. Can someone assist me in resolving this?
Initially, I attempted using a for loop:
for (i=0; i<schoolarray.length; i++) {
if (schoolarray[i]['school name'] === "") {
alert('School name is empty');
} else if (schoolarray[i]['school name'] !== "") {
alert('School name is not empty');
}
if (schoolarray[i]['school street'] === "") {
alert('School street is empty');
} else if (schoolarray[i]['school street'] !== "") {
alert('School street is not empty');
}
if (schoolarray[i]['school add'] === "") {
alert('School address is empty');
} else if (schoolarray[i]['school add'] !== "") {
alert('School address is not empty');
}
}
The error messages are not displaying correctly as different iterations yield different element messages.
Subsequently, I tried a foreach loop below with a similar issue. Can anyone provide suggestions?
School Array: [ { school name: "First School", school street: "First Street", school add : "First Address" }, { school name: "Second School", school street: "Second Street", school add : "Second Address" }, { school name: "Third School", school street: "Third Street", school add : "Third Address" } ]
if (schoolarray.length > 0 ) {
schoolarray.forEach(function(schoolObject, index) {
console.log(schoolObject['school name']);
Object.keys(schoolObject).forEach(function(prop) {
if(schoolObject['school name'] === "" ) {
alert('Please enter the school name');
} else if (schoolObject['school name'] !== "" ) {
alert('Good');
}
});
});
}