Search code examples
javascriptjavascript-objects

How to see if values are in the same "line" within an object in javascript


Not sure how to approach this problem, but I want to see if two values are in the same 'line'

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"]      } 
];

psuedocode of what I want to try to attempt

if(section.value && supplies.value in the same line) {
    return true;
}
else {
    return false;
}

//example 1
if("appliances" && "fridges" in the same line) {
    return true; //would return true
}
else {
    return false;
}

//example 2
if("plumbing" && "fridges" in the same line) {
    return true; 
}
else {
    return false; //would return false
}

Solution

  • By in the same line, you seem to mean defined within the same object in the array. If that's correct, the way to do that is like this:

    function inTheSameLine(section, supplies){
        return inventory_needed.some(obj => {
            return obj.section === section && (
                obj.supplies === supplies || (
                   Array.isArray(obj.supplies) && obj.supplies.includes(supplies)
                )
            );
        });
    }
    

    The JavaScript array some function returns true if any of the array elements satisfy the condition.