【发布时间】:2014-10-10 04:26:51
【问题描述】:
所以我在这里得到了一些棘手的东西。我有一个 JSON 对象,需要根据用户查询进行过滤。在这个 JSON 中,我想过滤掉 category_of_foods 字段,它是一组食物。
breakfastItems =
[
{
"id": 338,
"created_at": "2014-10-08T03:32:49.000Z",
"user_id": 91,
"type_of_meal": "breakfast",
"category_of_foods": [
"cheese burger",
"fruit"
]
},
{
"id": 339,
"created_at": "2014-10-08T03:34:43.000Z",
"user_id": 91,
"type_of_meal": "breakfast",
"category_of_foods": [
"chicken burger",
"fruit"
]
}
]
使用 Lo-Dash library ,当 category_of_foods 字段只是一个字符串而不是数组时,我能够使我的代码工作。我现在有以下不返回匹配项的代码:
$scope.showPicturesBreakfast = function(type, term){ // term = "fruit"
function filterBreakfast(category, list){
return _.filter(list, function(element){
return _(element.category_of_foods).forEach( function(entry){
return entry === category; // returns true twice if term is fruit
});
});
}
$scope.breakfastPictures = filterBreakfast(term, breakfastItems);
};
代码对我来说似乎是合乎逻辑的,因为它与以前相似,除了现在我还在遍历一个数组以找到真正的匹配项以返回 _.filter 函数。难道我做错了什么?
【问题讨论】:
标签: javascript arrays json angularjs lodash