【问题标题】:angular filter empty array in an object对象中的角度过滤器空数组
【发布时间】:2016-04-04 05:28:32
【问题描述】:

我有这个对象数组

var list = [{
    "questionId": 1,
    "correctChoiceIds": [],
    "choiceId": 0,
    "number": 1
}, {
    "questionId": 1,
    "correctChoiceIds": [1234, 4567],
    "choiceId": 0,
    "number": 2,
}, {
    "questionId": 2,
    "correctChoiceIds": [],
    "choiceId": 0,
    "number": 3
}];

//This filter gives me an array with list[0] and list[1]
var filterQuestion = $filter('filter')(list, { questionId: 1 }, true);

我想为他们的correctChoiceIds过滤所有具有空数组的人。

var filterNoCorrectChoice= $filter('filter')(list, { correctChoiceIds: [] }, true);

这是我想出的,但它根本没有给我任何东西。我不确定这是否是正确的方法,或者为什么它没有结果。

【问题讨论】:

    标签: javascript arrays angularjs angular-filters


    【解决方案1】:

    demo

    像这样使用过滤器,

      var filterNoCorrectChoice= $filter('filter')(list,function(item) {
            // must have array, and array must be empty
            return item.correctChoiceIds && item.correctChoiceIds.length === 0;
        });
    

    【讨论】:

      【解决方案2】:

      方法过滤器原生

      var filterQuestion = list.filter(function(el){ return el.correctChoiceIds.length<1; });
      // result
      console.log(filterQuestion);
      

      【讨论】:

        【解决方案3】:

        我想为他们的correctChoiceIds过滤所有具有空数组的人

        您不需要为此使用角度过滤器,使用标准的原生 javascript 过滤器...

        list.filter(x => !x.correctChoiceIds.length);
        

        【讨论】:

        • 这个也可以,但是我不太懂语法。我还是个初学者。
        • @riyu 您可以查看filterarrow functions 的文档,但基本上您正在过滤列表中具有空correctChoiceIds 数组的所有项目( x.correctChoiceIds.length === 0, 0 是 javascript 中的虚假值,这就是为什么我用 ! 否定条件的原因。希望现在更清楚;)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-29
        相关资源
        最近更新 更多