简体   繁体   English

比较输入与数组JavaScript

[英]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? 我是否正确地认为应该创建一个传递两个项目并对其进行for循环并按此答案中所述比较键的函数? Comparing Arrays of Objects in JavaScript 比较JavaScript中的对象数组

Thanks! 谢谢!

Regardless of how you're going to proceed, here's code that compares the input to a recipe: 无论您要如何进行,以下代码都会将input与配方进行比较:

 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. 对于mongodb查询,我想您会添加某种自定义过滤器来调用比较功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM