How to Access Both Key and Value for Each Object in an Array of Objects Using ng-repeat in AngularJS

Dec 07, 2025 · Programming · 9 views · 7.8

Keywords: AngularJS | ng-repeat | object iteration | key-value access | nested loops

Abstract: This article explores how to simultaneously retrieve the key (property name) and value of each object when iterating over an array of objects with the ng-repeat directive in AngularJS. By analyzing the nested ng-repeat method from the best answer, it explains its working principles, implementation steps, and potential applications. The article also compares alternative approaches like controller preprocessing and provides complete code examples with performance optimization tips to help developers handle complex data structures more efficiently.

Problem Background and Core Challenge

In AngularJS development, the ng-repeat directive is a core tool for iterating over arrays or object collections. However, when dealing with arrays containing multiple objects, developers often face a specific challenge: how to access both the key (i.e., property name) and the corresponding value of each object within the same iteration. For example, given the following data structure:

$scope.steps = [
    {companyName: true},
    {businessType: true},
    {physicalAddress: true}
];

Using simple ng-repeat syntax like <div ng-repeat="step in steps">, the step variable in each iteration only represents an object in the array (e.g., {companyName: true}). To directly obtain the key (e.g., 'companyName') and value (e.g., true), standard syntax does not support this, as ng-repeat defaults to using the array index rather than the object key as the key parameter. This leads to issues when developers attempt constructs like (stepName, isComplete) in steps, where stepName returns only the index value, not the desired object key.

Solution: Nested ng-repeat Method

The best answer proposes an efficient and intuitive solution: using nested ng-repeat directives to access both key and value simultaneously. The core idea is to use an outer loop to iterate over each object in the array and an inner loop to iterate over the properties of that object. The implementation is as follows:

<div ng-repeat="step in steps">
    <div ng-repeat="(key, value) in step">
        {{key}} : {{value}}
    </div>
</div>

In this code, the outer ng-repeat iterates over the steps array, assigning each object to the step variable per cycle. The inner ng-repeat uses the (key, value) syntax to traverse the properties of the step object, where key captures the property name (e.g., 'companyName') and value captures the property value (e.g., true). This method processes data directly in the view without additional controller logic, enhancing code simplicity and maintainability.

Technical Details and Working Mechanism

The nested ng-repeat method relies on AngularJS's data binding and directive parsing mechanisms. When AngularJS compiles the template, it creates a separate child scope for each ng-repeat. The outer loop generates a child scope for each object in the array, and the inner loop further iterates over the object's properties within that child scope. This allows the key and value variables to update dynamically in each inner iteration and be rendered in the DOM via expressions like {{key}} and {{value}}.

From a performance perspective, although nested loops may increase rendering overhead, for small or medium-sized datasets (e.g., the steps array in the example), the impact is usually negligible. In practical applications, it is recommended to combine this with AngularJS's track by optimization, such as <div ng-repeat="step in steps track by $index">, to reduce DOM operations and improve performance.

Alternative Approaches and Comparison

The controller preprocessing approach mentioned in the question is another common method. By restructuring data in the controller, for example:

$scope.stepNames = [];
angular.forEach($scope.steps, function(isComplete, stepName){
    $scope.stepNames.push({stepName: stepName, isComplete: isComplete});
});

And then iterating in the view with <div ng-repeat="item in stepNames">{{item.stepName}} : {{item.isComplete}}</div>. This method moves logic to the controller, making the view cleaner but increasing code complexity and maintenance costs. In contrast, the nested ng-repeat solution aligns better with AngularJS's declarative programming paradigm, expressing intent directly in the template, which facilitates debugging and team collaboration.

Practical Applications and Extensions

The nested ng-repeat method is not limited to simple boolean objects but can be extended to more complex data structures. For example, handling arrays of objects with multiple properties:

$scope.users = [
    {name: "Alice", age: 30, active: true},
    {name: "Bob", age: 25, active: false}
];

Through nested loops, all properties can be dynamically rendered:

<div ng-repeat="user in users">
    <div ng-repeat="(prop, val) in user">
        {{prop}}: {{val}}
    </div>
</div>

Additionally, combining with AngularJS filters (e.g., limitTo or orderBy) enables more flexible view control, such as displaying only specific properties or sorting by value.

Conclusion and Best Practices

In AngularJS, by using nested ng-repeat directives, developers can efficiently access both keys and values when iterating over arrays of objects. This method simplifies view logic, reduces controller burden, and enhances code readability. For performance-sensitive scenarios, it is advisable to use track by for optimization and consider the impact of data size on rendering. Overall, the nested loop solution is the preferred approach for handling such problems, demonstrating the powerful capabilities of AngularJS data binding.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.