Is there a way to see if an item is located in a dictionary values.
My attempt:
var inventory_needed = [
{ section: "hardware", supplies: "hammers" },
{ section: "plumbing", supplies: "pipes" },
{ section: "garden", supplies: "grass seeds" },
{ section: "cleaning supplies", supplies: ["hand sanitizer", "detergent"] },
{ section: "appliances", supplies: ["fridges", "dishwashers"] }
];
incoming_item = "hand sanitizer";
inventory_needed.forEach(function(item) {
if(item.supplies.includes(incoming_item)) {
console.log(incoming_item + 'is on the way');
}
else{
console.log('nothing is on the way');
}
}
You could simplify your search this way:
if (inventory_needed.some(item => item.supplies.includes(incoming_item))) {
console.log(incoming_item + ' is on the way');
} else {
console.log('nothing is on the way');
}
This will only ever output once. It's not clear whether or not you want the is on the way message to be able to print multiple times.
Array.prototype.some() will let you run a true/false check for each element in the list, and returns whether or not any of them were true.
Since your supplies array consist of both string and array, I suggest this below logic for you.
Logic
map through the array and generate list of supplies.Array.flat the array to make the array uni directional. I used Array.flatMap to combine both Array.map and Array.flatSet array using Set.has.Working Code
const inventory_needed = [
{ section: "hardware", supplies: "hammers" },
{ section: "plumbing", supplies: "pipes" },
{ section: "garden", supplies: "grass seeds" },
{ section: "cleaning supplies", supplies: ["hand sanitizer", "detergent"] },
{ section: "appliances", supplies: ["fridges", "dishwashers"] }
];
const incoming_item = "hand sanitizer";
const uniqueSuppliesList = new Set(inventory_needed.flatMap((item) => item.supplies));
uniqueSuppliesList.has(incoming_item) ? console.log(incoming_item + 'is on the way') : console.log('nothing is on the way');