Angular filter a object by its properties

后端 未结 6 2041
感情败类
感情败类 2020-11-30 04:47

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

{
          


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 05:30

    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.

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

    And that fiddle: http://jsfiddle.net/NqA8d/5/

提交回复
热议问题