AngularJS ng-repeat over an array of objects uniquely

I have an object with 2 arrays:

mainObject = { soccer: [], hockey: [] } 

Each of the arrays contains a different number of objects:

 sportObject = { soccer: [{equipment: "cleats"}, {shirt: "jersey"}, {team: "arsenal"}], hockey: [{equipment: "skates"}] } 

I print each object on the page using a list separated by "sport":

 <ul ng-repeat="(sport, value) in sportObject"> <li>{{sport}}</li> // Prints "soccer" or "hockey" <li ng-repeat="item in sportObject"></li> // <-- one of my failed attempts </ul> 

I want to print every object information in li under the correct sport name.

For example, there are a total of 4 objects, football has 3, hockey - 1.

Currently, each subject is repeated under both sports. Thus, both sports have 4 items. How can I use ng-repeat only to print equipment that falls under the correct sports title?

The result should look like this:

Football

  • equipment: spikes
  • shirt: shirt
  • team: arsenal

Hockey

  • equipment: skates
+6
source share
2 answers

The following should do the trick:

 <ul ng-repeat="(sport, value) in sportObject"> <li>{{sport}} <ul> <li ng-repeat="detail in value"> <span ng-repeat="(detailkey, detailvalue) in detail"> {{detailkey}} - {{detailvalue}} </span> </li> </ul> </li> </ul> 

Note that you need to do 3 iterations:

  • first over source object
  • second array object in each of the initial values โ€‹โ€‹of the object
  • third by objects inside arrays

And here is the working version for you: https://plnkr.co/edit/WKNRU6U6xwGgKRq4chhT?p=preview

+4
source

You can use key and value in the ng-repeat directive, as shown below.

 <ul ng-controller="SportController"> <strong>Soccer</strong> <li ng-repeat="(key,value) in sportObject.soccer"> {{value}} </li> <strong>Hockey</strong> <li ng-repeat="(key,value) in sportObject.hockey"> {{value}} </li> </ul> 

Additional set:

 var app = angular.module("sportApp", []); app.controller("SportController", function($scope) { $scope.sportObject = { soccer: [{equipment: "cleats"}, {shirt: "jersey"}, {team: "arsenal"}], hockey: [{equipment: "skates"}] } }); 

I created plunkr here to view and edit:

You can also attach the ng-repeat directive.

 <ul ng-controller="SportController"> <li ng-repeat="(sportName, sportValue) in sportObject"> {{sportName}} <ul ng-repeat="(key, val) in sportValue"> <li>{{val}}</li> </ul> </li> </ul> 
+1
source

Source: https://habr.com/ru/post/1014473/


All Articles