Suppose I have an object array like this:
var myArray = [
{"sandwich": "hamburger", "cheese": "cheddar" },
{"sandwich": "club", "cheese": "provolone" },
{"sandwich": "reuben", "cheese": "swiss" }
]
Now, I have a variable:
var sammy = "club"
In myArray I want to search for the item where "sandwich" is equal to the value of variable sammy and return the cheese: "provolone"
What is the simplest way to do this?
Using Array#find:
const
myArray = [ {"sandwich": "hamburger", "cheese": "cheddar" }, {"sandwich": "club", "cheese": "provolone" }, {"sandwich": "reuben", "cheese": "swiss" } ],
sammy = "club";
const { cheese } = myArray.find(({ sandwich }) => sandwich === sammy) || {};
console.log(cheese);