lemoney
lemoney

Reputation: 161

Get JSON Multidimensional Array Keys - AngularJS

I am trying to build a form out of a JSON array. I need to load the keys into the HTML. Here is an example of this array:

{
  "Fred": {
     "description": "A dude"
  },
  "Tomas": {
     "description": "Another Dude",
     "Work": {
       "Current": "No Employer",
       "Previous": "Enron"
     }
  }
}

What I was are the values Fred & Thomas. When I run this in Angular HTML:

<div ng-repeat="set in sets">
  <p ng-repeat="(key, val) in set">
    <span ng-bind="key"></span>: <span ng-bind="val"></span>
  </p>
</div>

I get the error "ngRepeat-dupes" although Fred and Tomas are not duplicate values. Any help is greatly appreciated.

Upvotes: 0

Views: 445

Answers (2)

ajmajmajma
ajmajmajma

Reputation: 14216

You are getting the dupe error from a key being the same in both objects. You can fix it by using track by $index, however in the data you have provided, there are no dupes... see fiddle - https://jsfiddle.net/t4q4nrfp/36/

IF you did have dupes in your data though you just add in track by $index (you can use other things as well index is generally a default) like so :

<div ng-repeat="set in sets track by $index"> << add here if you have dupes are this level
    <p ng-repeat="(key, val) in set track by $index"> << or here if dupes at this level
      <span ng-bind="key"></span>: {{val}} <span ng-bind="val"></span>
    </p>
</div>

Also, just to be clear, you are working with an object not an array.

Upvotes: 2

SoluableNonagon
SoluableNonagon

Reputation: 11755

use track by $index:

<div ng-repeat="set in sets track by $index">
  <p ng-repeat="(key, val) in set track by $index">
    <span ng-bind="key"></span>: <span ng-bind="val"></span>
  </p>
</div>

Upvotes: 0

Related Questions