If you are looking to check if meals have specific properties, the following function may be useful:
function hasPortion(meals) {
const portions = ["4", "3", "2", "1", "1/8", "1/4", "1/2"];
for (const prop in meals) {
const meal = meals[prop];
if (meal != undefined && meal.activado == "on" && portions.indexOf(meal.porcion) < 0) {
return false;
}
}
return true;
}
If you have more properties but only want to focus on checking these 10 properties, consider using this alternative approach:
function hasPortion(meals) {
const portions = ["4", "3", "2", "1", "1/8", "1/4", "1/2"];
for (let i = 1; i <= 10; i++) {
const prop = `meal${i}`;
const meal = meals[prop];
if (meal != undefined && meal.activado == "on" && portions.indexOf(meal.porcion) < 0) {
return false;
}
}
return true;
}
New solution suggestion:
Consider utilizing an Array to store all meal items and a Set to store portions for efficient searching.
const meals = [
{ activado: "on", porcion: "4" },
{ activado: "on", porcion: "1/8" },
{ activado: "on", porcion: "3" },
{ activado: "on", porcion: "1/2" },
];
function hasPortion(meals) {
const portions = new Set(["4", "3", "2", "1", "1/8", "1/4", "1/2"]);
return !meals.some((meal) => meal.activado === "on" && !portions.has(meal.porcion));
}
// Example usage
console.log(hasPortion(meals)); // Output: true
// Add a non-matching item
meals.push({ activado: "on", porcion: "1/3" })
console.log(hasPortion(meals)); // Output: false