roo roo - 4 days ago 4
Node.js Question

Compare input to array javascript

I currently have the following structure:

"name" : 'Invisibility',
"ingredients" : {
"CatTail" : 2,
"Arsenic" : 1,
"Newt" : 2,
},
"name" : "Super Strength",
"ingredients" : {
"Plutonium" : 2,
"CatPee" : 5,
"Rock" : 10
}


I'm taking input as an array in the following way:

input = {
firstIngredient : firstQuantity,
secondIngredient : secondQuantity,
thirdIngredient : thirdQuantity,
}


The idea is that I have a list of ingredients and quantities as input and now I want to see if the submitted values match one of the ingredients above.

Am I correct in thinking that I should create a function passing both items and doing a for loop over them and compare keys as described in this answer? Comparing Arrays of Objects in JavaScript

Thanks!

Answer

Regardless of how you're going to proceed, here's code that compares the input to a recipe:

var recipes = [{
  "name": 'Invisibility',
  "ingredients": {
    "CatTail": 2,
    "Arsenic": 1,
    "Newt": 2,
  }
}, {
  "name": "Super Strength",
  "ingredients": {
    "Plutonium": 2,
    "CatPee": 5,
    "Rock": 10
  }
}];

var input = {
  "CatPee": 5,
  "Rock": 10,
  "Plutonium": 2,
};

function matches(a, b) {
  var match = true;
  Object.keys(a).forEach(ingredient => {
    if (a[ingredient] !== b[ingredient]) match = false;
  });
  return match;
}

recipes.forEach(recipe => {
  if (matches(input, recipe.ingredients)) console.log("match found: " + recipe.name);
});

In the case of a mongodb query I guess you'd add some kind of custom filter which calls the comparison function.