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.

1

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
with a loop in your object then you will have mytest.specialities[loopindex].name Or like @Arif wrote
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>

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.