Angular 根据对象的属性过滤对象 [英] Angular filter a object by its properties

查看:37
本文介绍了Angular 根据对象的属性过滤对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有一系列对象属性的对象,该对象具有以下类似结构(这是数据从服务返回的方式):

I have an object with a series of object properties that is in the following similar structure (which is the way the data is coming back from a service):

{
  "1": {
    "type": "foo",
    "name": "blah"
  },
  "2": {
    "type": "bar"
  },
  "3": {
    "type": "foo"
  },
  "4": {
    "type": "baz"
  },
  "5": {
    "type": "test"
  }
}

当我执行 ng-repeat 时,我可以遍历所有 5 个对象,例如:

When I do a ng-repeat, I can iterate over all 5 of these object, something like:

<div ng-repeat="item in items">{{item.type}}</div>

然而,我真正想做的是只迭代那些不是foo"类型的项目,即 3 次迭代而不是 5 次.我知道可以以某种方式利用过滤器来做这个,但我不确定如何.我尝试了以下方法:

However, what I really want to do is iterate only over those items that are NOT the type "foo", namely 3 iterations instead of 5. I know that filters can somehow be leveraged to do this, but I am not sure how. I tried the following:

<div ng-repeat="item in items| !filter:{type:'foo'}">{{item.type}}</div>

但这不起作用.事实上,即使执行以下操作以限制为仅 2 个对象(那些带有 item.type==="foo" 的对象),它也不起作用并进行 5 次迭代:

but this doesn't work. In fact, even doing the following to limit to just 2 objects(those with item.type==="foo"), it doesn't work and does 5 iterations:

<div ng-repeat="item in items| filter:{type:'foo'}">{{item.type}}</div>

本质上,我想做类似的事情:

In essence, I want to do something similar to:

<div ng-repeat="item in items" ng-if="item.type !=='foo'>{{item.type}}</div>

但是,我知道一个行不通.

However, I know that one doesn't work.

推荐答案

过滤器适用于数组,但您有一个对象字面量.

Filter works on arrays but you have an object literal.

因此,您可以将对象字面量转换为数组,也可以创建自己的过滤器,而不是接收对象字面量.

So you can either convert your object literal into an array or create your own filter than takes in the object literal.

如果您不需要这些索引值,那么转换为数组可能是您最好的选择(这是数组工作的小提琴:http://jsfiddle.net/NqA8d/3/):

If you don't need those index values then converting to an array may be your best bet( Here's a fiddle with the array working: http://jsfiddle.net/NqA8d/3/):

$scope.items = [{
    "type": "foo",
        "name": "blah"
}, {
    "type": "bar"
}, {
    "type": "foo"
}, {
    "type": "baz"
}, {
    "type": "test"
}];

如果您想进行过滤,这里有一种方法:

In case you'd like to do a filter, here's one way to do that:

myApp.filter('myFilter', function () {
    return function (items, search) {
        var result = [];
        angular.forEach(items, function (value, key) {
            angular.forEach(value, function (value2, key2) {
                if (value2 === search) {
                    result.push(value2);
                }
            })
        });
        return result;

    }
});

那个小提琴:http://jsfiddle.net/NqA8d/5/

这篇关于Angular 根据对象的属性过滤对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆