如何检查用户输入数组是否等于特定对象?

时间:2018-09-17 11:27:55

标签: javascript arrays

我有一个存储用户输入的数组,并且我有一些需要特定值才能为真的对象。用户输入必须匹配每个对象中的成分。

var recipes = [
{
    'name': 'Omelette',
    'ingredients': [
        "Eggs",
        "Mushrooms",
        "Peppers",
        "Onions"
    ]
},
{
    'name': 'Spaghetti',
    'ingredients': [
        "Pasta",
        "Tomato",
        "Meat Balls"
    ]
};

var storedIngredients = [];
//This is the array that stores user input.
//I used this is so far but it's hardcoded and I don't want hardcode

if (storedIngredients.includes('Pasta','Tomato','Meat Balls') {
console.log(recipes.name[0];);
};

我需要一种方法来让用户输入相应的配料,例如,他将被证明具有烹制意大利面条的配料。

2 个答案:

答案 0 :(得分:3)

您可以在数组上使用过滤器来查找用户具有其成分的食谱列表。

kent$  cat f
1 10
2 15
3 1
5 50
8 990

kent$  awk 'NR==FNR{a[$1]=$0;next}{print $1 in a?a[$1]:$1 FS 0}' f <(seq 10)
1 10
2 15
3 1
4 0
5 50
6 0
7 0
8 990
9 0
10 0

答案 1 :(得分:0)

您可以在食谱数组上使用reduce,然后用户可以制作的每个食谱将其推入新数组。

var recipes = [
{
    'name': 'Omelette',
    'ingredients': [
        "Eggs",
        "Mushrooms",
        "Peppers",
        "Onions"
    ]
},
{
    'name': 'Spaghetti',
    'ingredients': [
        "Pasta",
        "Tomato",
        "Meat Balls"
    ]
}]

var storedIngredients = ['Pasta', 'Tomato', 'Meat Balls'];
//This is the array that stores user input.
//I used this is so far but it's hardcoded and I don't want hardcode

let result = recipes.reduce((acc, n) => {
  let ingredients = n.ingredients;
  if (storedIngredients.includes(...ingredients)) acc.push(n.name);
  return acc;
}, [])
console.log(result);