我是这里的新手,正在学习 JS 和 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 中实现这一目标? 任何帮助将不胜感激。 谢谢。
最佳答案
这不是 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
忽略它(过滤掉)
关于javascript - 如何通过特定字段过滤 JSON 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37083223/