2017-06-20 60 views
0

目前,我有以下結構:比較輸入到陣列的JavaScript

"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

第一個「東西」應該是什麼?它既不是一個數組,也不是一個對象,也不是一個對象數組......'input'是一個對象而不是一個數組。 – Andreas

+0

你的第一個結構看起來不合適;您不能擁有多個具有相同名稱的密鑰。 –

+0

嗯,好吧,我把它插入到下面的mongo集合中。有沒有更好的結構方式? '\t db.collection( '食譜')插入({ \t \t 「姓名」: '隱形', \t \t 「成分」:{ \t \t \t 「香蒲」:2, \t \t \t 「砷」 :1, \t \t \t 「蠑螈」 \t:2, \t \t}, \t \t 「名」: 「超級力量」, \t \t「荷蘭國際集團redients」:{ \t \t \t 「鈈」:2, \t \t \t 「CatPee」:5, \t \t \t 「搖滾」:10 \t \t} \t});' – roo

回答

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中查詢我想你想補充的情況下,某種調用比較函數的自定義過濾器。

+0

啊這是有幫助的!結構現在更有意義:) - 謝謝! – roo