对象中的角度过滤器空数组

angular filter empty array in an object

本文关键字:过滤器 数组 对象      更新时间:2023-12-14

我有这个对象数组

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);

这就是我想到的,但它根本没有给我任何东西。我不确定这是否是正确的方式,也不确定为什么会一无所获。

请参阅演示

使用这样的过滤器,

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

方法过滤本机

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

我想为他们的correctChoiceIds 筛选所有具有空数组的

你不需要一个角度过滤器,使用一个标准的本地javascript过滤器。。。

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