Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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.

share|improve this question
    
Possible duplicate of Access / process (nested) objects, arrays or JSON – Juhana Aug 10 at 8:37

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)';

share|improve this answer
    
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 at 8:43
    
with a loop in your object then you will have mytest.specialities[loopindex].name Or like @Arif wrote – DMCISSOKHO Aug 10 at 8:44

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>
share|improve this answer

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.