I have multiple nested collections of JavaScript objects and I believe there has to be a more efficient way to achieve what I'm doing. The goal is to access the values of the fields in Objects 1, 2, and 3 and check if they are true or false. Below is my current code:
var valid = [];
if (objects instanceof Array) {
for (var i = 0; i < objects.length; i++) {
var fieldIsFull = [];
// Loop through all fields to check if empty and build array
for (var j = 0; j < objects[i].Fields.length; j++) {
if (objects[i].Fields[j].isRequired) {
if (objects[i].Fields[j].Value != null ||
objects[i].Fields[j].Value != undefined) {
fieldIsFull.push(true);
} else {
fieldIsFull.push(false);
}
}
}
// Check array for any false value.
if ($.inArray(false, fieldIsFull) >= 0) {
valid.push(false);
} else {
valid.push(true);
}
}
// Check array for any false value.
if ($.inArray(false, valid) >= 0) {
return false;
} else {
return true;
}
If anyone has suggestions on a more optimized approach to accomplish this task, I would greatly appreciate it.
SOLUTION: After some experimentation, I came up with the following revised code as I only needed the false value:
if (objects instanceof Array) {
for (var i = 0; i < objects.length; i++) {
// Loop through all fields to check if empty
for (var j = 0; j < objects[i].Fields.length; j++) {
if (objects[i].Fields[j].isRequired) {
if (objects[i].Fields[j].Value == null) {
return false;
}
}
}
}
return true;