0

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!

Chris Sharp
  • 2,005
  • 1
  • 18
  • 32
roo
  • 343
  • 1
  • 5
  • 17
  • What should the first "thing" be? It's neither an array nor an object nor an array of objects... `input` is an object and not an array. – Andreas Jun 20 '17 at 16:10
  • Your first structure looks off; you can't have multiple keys with the same name. –  Jun 20 '17 at 16:10
  • Hmmm ok, I was inserting it into a mongo collection like below. Is there a better way to structure? ` db.collection('recipes').insert( { "name" : 'Invisibility', "ingredients" : { "CatTail" : 2, "Arsenic" : 1, "Newt" : 2, }, "name" : "Super Strength", "ingredients" : { "Plutonium" : 2, "CatPee" : 5, "Rock" : 10 } });` – roo Jun 20 '17 at 16:12
  • You might want to build a query that compares the input to each recipe. –  Jun 20 '17 at 16:17
  • Hi @ChrisG, thanks for the advice. I'm a bit of a noob when it comes to JS so is there a good resource to look at for this? – roo Jun 20 '17 at 16:21

1 Answers1

0

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.