Mjeduar
Mjeduar

Reputation: 97

How to watch an object within object in angularjs

I have tried different ways to access an Array, I haven't been able

This is my array:

Sites [ 
{
    "0": { 
        "catf": 
        { 
            "2": { "cats": { "id": "9" } }, 
            "4": { "cats": { "id": "12" } }, 
            "5": { "cats": { "id": "13" } } 
        } 
    } 
}, 
{ 
    "1": { 
        "catf": 
        { 
            "2": { "cats": { "id": "10" } }, 
            "4": { "cats": { "id": "11" } } 
        } 
    } 
}]

This is how I am trying to access the array

$scope.proposal2.sites[0].catf[2];

this is the error

Cannot read property '2' of undefined

When I print console.log($scope.proposal2.sites[0]) I got this

 Object {0: Object, $$hashKey: "00L"} >0: Object >catf: Object >2: Object >cats: Object id: >"10"

How could I access it?

Thanks,

Upvotes: 0

Views: 447

Answers (3)

Mjeduar
Mjeduar

Reputation: 97

I found the answer to my problem is: $scope.proposal2.sites[0][0].catf[2]

Thanks to everyone

Upvotes: 0

SET001
SET001

Reputation: 11708

In your code you declared array with two objects. To access first of them you should use $scope.proposal2.sites[0]. Then this object have only one key - 0:

{
    "0": { 
        "catf": 
        { 
            "2": { "cats": { "id": "9" } }, 
            "4": { "cats": { "id": "12" } }, 
            "5": { "cats": { "id": "13" } } 
        } 
    } 
}, 

so you accessing it with $scope.proposal2.sites[0][0] to get object with only one key catf:

{ 
   "catf":{ 
       "2": { "cats": { "id": "10" } }, 
       "4": { "cats": { "id": "11" } } 
   }
}

so now you use $scope.proposal2.sites[0][0].catf[2] to access what you want.

Also I agreed with charlietfl`s comments in that your structure looks too complicated and maybe you would like to have something like this:

[ 
  {"catf": { 
    "2": { "cats": { "id": "9" } }, 
    "4": { "cats": { "id": "12" } }, 
    "5": { "cats": { "id": "13" } } 
    }
  },
  {"catf": { 
    "2": { "cats": { "id": "10" } }, 
    "4": { "cats": { "id": "11" } } 
    }
  }
]

and access it with $scope.proposal2.sites[0].catf[2]

Also I believe than even this structure can (and should) be simplified, but to go with it, you should give more information about your task.

Upvotes: 1

karthik pamidimarri
karthik pamidimarri

Reputation: 305

$scope.proposal2.sites[0].catf[2];

In the above line of code, sites is an array object, so here you could access the data, but catf is an Object, so you are getting issue like "Cannot read property '2' of undefined".

Upvotes: 1

Related Questions