对象分配了多个json对象时无法过滤

时间:2018-08-06 21:05:59

标签: angularjs json angularjs-filter

我的角度控制器中有一个如下所示的对象。

$scope.updatedList = [
  [
    {
      "sId":100,
      "s1":12,
      "s2":1,
      "s3":3,
      "spread":"21x",
      "owner":"Michael",
      "labels":"deffered incomplete"
    }
  ],
  [
    {
      "sId":3432,
      "s1":1,
      "s2":10,
      "s3":20,
      "spread":"34",
      "owner":"Taillor",
      "labels":"complete"
    },
    {
      "sId":4000,
      "s1":8,
      "s2":2,
      "s3":3,
      "spread":"332",
      "owner":"Shan",
      "labels":"complete deffered"
    }
  ],
  [],
  []
];

我正在尝试从JSON对象($ scope.updatedList)过滤列表。 下面是js代码,如果属性标签的字面有所变化,我将尝试仅显示json对象中的元素。

演示:https://plnkr.co/edit/37bnDR1fkNXYBcBP6vEW?p=preview

$scope.showList = function(){
    console.log("showList  " + JSON.stringify($scope.updatedList));
    $scope.defferedList = $scope.updatedList.filter(function(obj) {
        console.log(obj.labels && obj.labels.includes('deffered'));
        return obj.labels && obj.labels.includes('deffered');
    });
};

PS:$scope.updatedList具有多个以逗号分隔的json对象,定义为一个对象。

-编辑---预期输出:

我要从$scope.updatedList中删除属性为“ lables”的元素,其中不包含单词“ deffered”。

$scope.defferedList = [[{"sId":100,"s1":12,"s2":1,"s3":3,"spread":"21x","owner":"Michael","labels":"deffered incomplete"}],[{"sId":4000,"s1":8,"s2":2,"s3":3,"spread":"332","owner":"Shan","labels":"complete deffered"}],[],[]];

在$ scope.defferedList中,我删除了$ scope.updatedList的labels属性中没有单词“ deffered”的元素。

1 个答案:

答案 0 :(得分:0)

执行此操作的方法可能更优雅,但这会将您的预期输出放入$scope.defferedList属性中:

$scope.showList = function(){
    $scope.defferedList = [];

    $scope.updatedList.forEach(function(item) {
        $scope.defferedList.push(
            item.filter(function(subItem) {
                return subItem.labels.includes('deffered');
            })
        );
    });
};