Search code examples
angularjsangularjs-ng-repeat

Using ng-repeat on nested array of objects


Below is my JSON object and I am trying to show the same in html table.

$scope.results = {
  "data": [
    {
      "name": "Sam",
      "details": [
        {
          "official": [
            {
              "address1": "Link road",
              "pincode": 76755554
            },
            {
              "address1": "K main road",
              "pincode": 9766565
            }
          ]
        },
        {
          "name": "John",
          "details": [
            {
              "official": [
                {
                  "address1": "Old college road",
                  "pincode": 11111
                },
                {
                  "address1": "near east side",
                  "pincode": 6555446
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}

I have used ng-repeat to achieve the below output. But I am not getting the expected result Final output table

This is the code which I have tried and got stuck JSFIDDLE

Any idea on how to achieve my expected result will be really helpful.


Solution

  • You may have to tweak this slightly if your data structure can get more complicated when there are more levels, but this should reformat your data and flatten everything into an array of people without all the different levels.

    $scope.peopleFlat = [];
    
    function flattenPeople(people) {
        people.forEach((person) => {
            $scope.peopleFlat.push({
               name: person.name,
               addresses: person.details[0].official
            });
    
            if (person.details.length > 1) {
                flattenPeople([person.details[1]]);
            }
        });
    }
    
    flattenPeople($scope.people);
    

    Then you can use a combination of ng-repeat-start and ng-repeat-end to make it work using rowspan instead of a nested <table> element.

    <table class="table table-bordered table-condensed">
        <tr>
            <th>Name</th>
            <th>Address</th>
            <th>Pincode</th>
        </tr>
        <tr ng-repeat-start="person in peopleFlat">
            <td rowspan="{{person.addresses.length || 1}}">{{person.name}}</td>
            <td>{{person.addresses.length ? person.addresses[0].address1 : ''}}</td>
            <td>{{person.addresses.length ? person.addresses[0].pincode : ''}}</td>
        </tr>
        <tr ng-repeat-end ng-repeat="address in person.addresses.slice(1)">
            <td>{{address.address1}}</td>
            <td>{{address.pincode}}</td>
        </tr>
    </table>