Search code examples
arraysangularjsjavascript-objects

Loop through array of arrays containing objects


This is my first time posting and I'm also very new to AngularJs and somewhat new to JavaScript in general. I hope I am providing enough info. I have an array containing arrays of objects [[{},{},{}],[{},{},{}],[{},{},{}]]. Is there a way to loop through this using AngularJs and output something similar to the following?

Group Title 1

  • 01 Item title 1: item description
  • 02 Item title 2: item description

Group Title 2

  • 03 Item title 1: item description
  • 04 Item title 2: item description

==============

$scope.groups_array = [
    [
        {
            "id": "01 ",
            "": [
                "Item Title 1",
                "Item description"
            ],
            "group_id": "A",
            "title": "Group Title 1"
        },
        {
            "id": "02 ",
            "": [
                "Item Title 2",
                "Item description"
            ],
            "group_id": "A",
            "title": "Group Title 1"
        }
    ],
    [
        {
            "id": "03 ",
            "": [
                "Item Title 1",
                "Item description"
            ],
            "group_id": "B",
            "title": "Group Title 2"
        },
        {
            "id": "04 ",
            "": [
                "Item Title 2",
                "Item description"
            ],
            "group_id": "B",
            "title": "Group Title 2"
        }
    ]
]

$scope.group_title = ["Group Title 1", "Group Title 2"];
<div>
    <div ng-repeat="title in group_title">
        <h1>{{title}}</h1>
        <ul>
            <li ng-repeat="item in groups_array">
              {{item.id + ' ' + item[''][0]}}: {{item[''][1]}}
            </li>
        </ul>
    </div>
</div>

The output I'm getting instead is simply a list of the :'s with no errors in the console.

The arrays of objects themselves come from a master array containing all the objects, and I tried to group them into arrays by group title. I'm not sure if this is the best solution.


Solution

  • The nested ng-repeat needs to select the correct group to iterate:

    <div>
        <div ng-repeat="title in group_title">
            <h1>{{title}}</h1>
            <ul>
                ̶<̶l̶i̶ ̶n̶g̶-̶r̶e̶p̶e̶a̶t̶=̶"̶i̶t̶e̶m̶ ̶i̶n̶ ̶g̶r̶o̶u̶p̶s̶_̶a̶r̶r̶a̶y̶"̶>̶
                <li ng-repeat="item in groups_array[$index]">
                  {{item.id + ' ' + item[''][0]}}: {{item[''][1]}}
                </li>
            </ul>
        </div>
    </div>
    

    This assumes that the order of the titles in the group_title array matches the order of the groups in the groups_array.