【问题标题】:How to iterate through an array in the callback function of _.filter using Lo-dash如何使用 Lo-dash 遍历 _.filter 回调函数中的数组
【发布时间】: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


    【解决方案1】:

    你必须向调用者返回一个真值或假值,在这种情况下是filter。尝试改用some,它会返回一个布尔值:

    return _(element.category_of_foods).some(function(entry){
        return entry === category;
    

    如果至少有一个条目匹配,它将返回true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-23
      • 2020-10-11
      • 1970-01-01
      • 2021-01-11
      • 2012-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多