2016-05-07 55 views
1

我是新手,學習JS和JSON。 嗯,我有JSON數據爲:如何通過特定字段過濾掉JSON數據?

{ 
     "month":"november", 
     "category":"coffee", 
     "price":50, 
     "name":"Pike Place Roast Brewed Coffee Verismo Pods", 
     "flavor":"flavored", 
     "count":5, 
     "roast":"medium", 
     "type":"regular" 
    }, 
    { 
     "month":"august", 
     "category":"coffee", 
     "price":40, 
     "name":"Starbucks VIA Ready Brew French Roast", 
     "flavor":"flavored", 
     "count":548, 
     "roast":"blonde", 
     "type":"decaffinated" 
    }, 
    { 
     "month":"november", 
     "category":"coffee", 
     "price":50, 
     "name":"Starbucks Caffé Verona Blend, Whole Bean", 
     "flavor":"flavored", 
     "count":5, 
     "roast":"medium", 
     "type":"regular" 
    }, 
    { 
     "month":"asia-pacific", 
     "category":"coffee", 
     "price":20, 
     "name":"Starbucks Caffè Verona K-Cup Pods", 
     "flavor":"flavored", 
     "count":3, 
     "roast":"dark", 
     "type":"regular" 
    }, 
    { 
     "month":"august", 
     "category":"coffee", 
     "price":40, 
     "name":"Milk Verismo Pods", 
     "flavor":"flavored", 
     "count":233, 
     "roast":"blonde", 
     "type":"decaffinated" 
    }, 
    { 
     "month":"november", 
     "category":"coffee", 
     "price":50, 
     "name":"Starbucks VIA Ready Brew Decaf Italian Roast", 
     "flavor":"flavored", 
     "count":5, 
     "roast":"medium", 
     "type":"regular" 
    }, 
    { 
     "month":"august", 
     "category":"coffee", 
     "price":40, 
     "name":"Guatemala Antigua Espresso Verismo Pods", 
     "flavor":"flavored", 
     "count":587, 
     "roast":"blonde", 
     "type":"decaffinated" 
    } 

現在假設我想獲得的所有數據有關的月份(如11月)我怎麼能在Javascript實現這一目標? 任何幫助將不勝感激。 謝謝。

回答

0

這不是JSON,但我假設它是一個部分數組。

var result = theArray.filter(function(value){ 
    return value.month === "November"; // or whatever you filter on 
}); 

// result is now a filter array containing only month === 'November' 

它是如何工作的?

過濾數組中的每個項目(value)。如果您返回true,則將其添加到新陣列中。 false忽略它(過濾掉)

+0

非常感謝! 這幫了我:) –