Javascript Startup of Objects

Asked

Viewed 862 times

5

I’m new to Javascript, and I’m using a framework Restangular written with Angularjs for HTTPS requests. I’m having a hard time 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 that I initialized an object:

$scope.perfilDeAcesso = {}; 

here I initialized a array inside my object:

$scope.perfilDeAcesso.itensPerfilDeAcesso = []; 

the structure of my object at the end should be more or less that:

perfilDeAcesso = {itensPerfilDeAcesso[]} 

and itensperfilDecesso must have a structure similar to:

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

My problem

Cannot set Property xxx of Undefined

is in initializing 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);
    } 
})
  • Hi, Luiz, welcome to [en.so]. Please check out the http://answall.com/editing-help guide

  • This question seems to be decontextualized because it solves a specific problem of the PA and will serve no one else in the future.

1 answer

7


Like $scope.perfilDeAcesso.itensPerfilDeAcesso is an empty array, $scope.perfilDeAcesso.itensPerfilDeAcesso[int] returns undefined. You must 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 the literal object syntax:

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

    I researched a lot and found nothing, with three characters I solved my problem, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.