1

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>

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.