我目前有以下结构:
"name" : 'Invisibility',
"ingredients" : {
"CatTail" : 2,
"Arsenic" : 1,
"Newt" : 2,
},
"name" : "Super Strength",
"ingredients" : {
"Plutonium" : 2,
"CatPee" : 5,
"Rock" : 10
}
我以下列方式将输入作为数组:
input = {
firstIngredient : firstQuantity,
secondIngredient : secondQuantity,
thirdIngredient : thirdQuantity,
}
我的想法是我有一个成分和数量列表作为输入,现在我想看看提交的值是否与上述成分相符。
我认为我应该创建一个传递两个项目的函数并对它们进行for循环并比较这个答案中描述的密钥吗? Comparing Arrays of Objects in JavaScript
谢谢!
答案 0 :(得分:0)
无论您要如何继续,这里的代码都会将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);
});

对于mongodb查询,我猜你要添加某种调用比较函数的自定义过滤器。