JavaScript Initialization of Objects [closed]

4

I'm new to JavaScript, and I'm using a framework Restart written with AngularJs for HTTPS requests. I'm having a lot of trouble initializing a literal object, with the following structure:

$scope.niveisDeAcesso = [
    {nivel:"LISTAR", selected: false},
    {nivel:"ADICIONAR", selected: false},
    {nivel:"EDITAR", selected: false},
    {nivel:"EXCLUIR", selected: false}
];

In this section I initialized an object:

$scope.perfilDeAcesso = {}; 

Here I initialized an array within my object:

$scope.perfilDeAcesso.itensPerfilDeAcesso = []; 

The structure of my object in the end should be more or less this:

perfilDeAcesso = {itensPerfilDeAcesso[]} 

and itemsProfileProcess should have a structure similar to:

itemPerfilDeAcesso = { itemDeAcesso: {...}, niveisDeAcesso: [...]}

My problem

  

Can not set property xxx of undefined

This is to initialize the itensPerfilDeAcesso so that I can receive the itemDeAcesso :

Restangular.all('itemdeacesso').getList().then(function(itens) { 
    for (var int = 0; int < itens.length; int++) {
        $scope.perfilDeAcesso.itensPerfilDeAcesso[int].itemDeAcess = 
            UtilService.limparDados(itens[int]);
        $scope.perfilDeAcesso.itensPerfilDeAcesso[int].niveisDeAcesso = 
            angular.copy($scope.niveisDeAcesso);
    } 
})
    
asked by anonymous 29.07.2014 / 03:37

1 answer

6

Since $scope.perfilDeAcesso.itensPerfilDeAcesso is an empty array, $scope.perfilDeAcesso.itensPerfilDeAcesso[int] returns undefined . You should initialize it as an empty object before assigning properties to it:

for (var int = 0; int < itens.length; int++) {
    $scope.perfilDeAcesso.itensPerfilDeAcesso[int] = {}; // inicialização do objeto
    $scope.perfilDeAcesso.itensPerfilDeAcesso[int].itemDeAcess = 
        UtilService.limparDados(itens[int]);
    $scope.perfilDeAcesso.itensPerfilDeAcesso[int].niveisDeAcesso = 
        angular.copy($scope.niveisDeAcesso);
}

We can also rewrite this code more cohesively using object literal syntax:

for (var int = 0; int < itens.length; int++) {
    $scope.perfilDeAcesso.itensPerfilDeAcesso[int] = {
        itemDeAcess: UtilService.limparDados(itens[int]),
        niveisDeAcesso: angular.copy($scope.niveisDeAcesso)
    };
}
    
29.07.2014 / 03:48