简体   繁体   中英

How group objects in array in array from ng-repeat with filter?

How group objects in array in array from ng-repeat with filter ?

I have an array with objects, and I would like group by this objects by their countries.

Sample : I would like to have this result :

Free : Australia, India, United States  
Pay : Australia
Not Pay : Australia, India

from :

{
"id": 1,
"offer": [
    {
        "id": 9806,
        "country": {
            "name": "Australia"
        },
        "code_show": [
            {
                "code": "Free"
            },
            {
                "code": "Pay"
            },
            {
                "code": "Not Pay"
            }
        ]
    },
    {
        "id": 9807,
        "country": {
            "name": "India"
        },
        "code_show": [
            {
                "code": "Free"
            },
            {
                "code": "Not Pay"
            }
        ]
    },
    {
        "id": 9808,
        "country": {
            "name": "United States"
        },
        "code_show": [
            {
                "code": "Free"
            }
        ]
    }
],
},
{
"id": 2,
"offer": [
    {
        "id": 9806,
        "country": {
            "name": "Australia"
        },
        "code_show": [
            {
                "code": "Free"
            },
            {
                "code": "Not Pay"
            }
        ]
    },
    {
        "id": 9807,
        "country": {
            "name": "Mexico"
        },
        "code_show": [
            {
                "code": "Free"
            }
        ]
    },
    {
        "id": 9808,
        "country": {
            "name": "United States"
        },
        "code_show": [
            {
                "code": "Free"
            }
        ]
    }
]
}

I tried this with the code :

<ul ng-repeat="(key, value) in offer.code_show | groupBy: 'code_show.code'">
  {{ key }}
  <li ng-repeat="country in value">
    : {{ country.name }} 
  </li>
</ul>

This might be better done in the controller - mainly cause you'll have a different data structure:

$scope.groupedByCode = {};
$scope.offer.forEach(function(obj) {
    obj["code_show"].forEach(function(code) {
        if (!$scope.groupedByCode[code]) {
            $scope.groupedByCode[code] = [];
        }

        $scope.groupedByCode[code].push(obj);
    });
});

Now you'll have each offer object in a key with the name of the code, then just make the view:

<ul ng-repeat="(key, value) in groupedByCode">
    {{ key }}
    <li ng-repeat="country in value">
        : {{ country.country.name }} 
    </li>
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM