0

Here is my Json data

"data": {
      "address": {
        "postalCode": "112629",
        "state": "DL",
        "city": "new city",
        "streetAddress": "my street"
      },
     "specialities": [
        {
          "_id": "577692f7",
          "name": "Football",
          "description": "game",
          "__v": 0
        }
      ]
    }

$scope.test = data; i am fetching data in html by ng-repeat="mytest in test" than

mytest.address.city // this is working fine
mytest.specialities.name // not printing anything

i am facing the problem in accessing the specialities name i think that is because of specialities is a array but don't know how to get it.

Harsh sachdev
  • 217
  • 1
  • 2
  • 13
  • Possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – JJJ Aug 10 '16 at 08:37

3 Answers3

2

You defined a specialities object with only one array inside

try

mytest.specialities[0].name 

Update:

Also you may want to make sure that the array has at least one element, otherwise you mayget a TypeError: Cannot read property 'name' of undefined.

So the code sould look like this:

mytest.specialities.length > 0 ? mytest.specialities[0].name : '(some default value)';

Dan M. CISSOKHO
  • 1,070
  • 1
  • 12
  • 27
  • Thanks for comment. you are right this is the way but what if i have more than one entries of specialties and i don't know how many are there like someone has 3 someone has 4 that how will i fetch. – Harsh sachdev Aug 10 '16 at 08:43
  • with a loop in your object then you will have mytest.specialities[loopindex].name Or like @Arif wrote – Dan M. CISSOKHO Aug 10 '16 at 08:44
0

Yes mytest.specialities is array. JSON has two possible options [ ] - array, { } - object. In this situation we have array of objects - [ { /* object data */ } ] so to get object parameter first go to array element like this ( example getting first element on index 0 ):

mytest.specialities[0].name 

second element:

mytest.specialities[1].name 

example each:

<div  ng-repeat="special in mytest.specialities">
    <span>{{special.name}}</span>
</div>

of course before that set mytest to scope like:

$scope.mytest=mytest;//mytest is your data structure
Maciej Sikora
  • 19,374
  • 4
  • 49
  • 50
0

Assuming there will be many specialities you should use ng-repeat to display them all.

<p ng-repeat="s in mytest.specialities"> {{s.name}} / {{s._id}} / {{s.description}} </p>
Arif
  • 1,617
  • 9
  • 18