length of a json in angularjs

0

There is some function in angular 1.6 to know the number of records that the json brings, I want to know from my controller, I have used $scope.count = Object.keys($scope.data).length ; but throws me 2, when my json brings 8 records, also use $scope.count=$scope.data.length ; and it gives me 0.

$scope.tecnicos = TecnicoResource.query(); 

$ scope.count = Object.keys ($ scope.tecnicos) .length; console.log ($ scope.count);

JSON

{ 
  "id_usuario": 5, 
  "nombre": "Oscar Javier", 
  "puesto": "Personal de soporte técnico", 
  "perfil_id": 6, 
  "empresa_id": 1, 
  "nombre_usuario": "ovivas", 
  "correo": "[email protected]", 
  "activo": 1, 
  "deleted_at": null, 
  "created_at": "2016-07-26 17:50:38", 
  "updated_at": "2016-10-05 22:12:51", 
  "carga_trabajo": 0 
}
    
asked by Raymundo c.o 21.04.2017 в 00:59
source

1 answer

1

Remember that JSON objects are only a collection of attributes, and therefore, if you want to see the length of an object like this:

{ 
  "id_usuario": 5, 
  "nombre": "Oscar Javier", 
  "puesto": "Personal de soporte técnico", 
  "perfil_id": 6, 
  "empresa_id": 1, 
  "nombre_usuario": "ovivas", 
  "correo": "[email protected]", 
  "activo": 1, 
  "deleted_at": null, 
  "created_at": "2016-07-26 17:50:38", 
  "updated_at": "2016-10-05 22:12:51", 
  "carga_trabajo": 0 
}

The length will be 0 , however if you want to have an array of JSON objects, it should be something like this:

tecnicos = [
    {
       nombre: Jose,
       apellido: Perez,
       edad: 18
    },
    {
       nombre: Carlos,
       apellido: Garcia,
       edad: 14
    },
    {
       nombre: Maria,
       apellido: Martinez,
       edad: 22
    }
]

Then you can do tecnicos.length without problem.

However, in the way that you are declaring the JSON is wrong, because when you have quotation marks for attribute names, the object stops having keys, therefore it stops being an object because it does not have the format (key, value) that handles all objects.

Try removing the quotes like this:

 $scope.tecnicos = { 
      id_usuario: 5, 
      nombre: "Oscar Javier", 
      puesto: "Personal de soporte técnico", 
      perfil_id: 6, 
      empresa_id: 1, 
      nombre_usuario: "ovivas", 
      correo: "[email protected]", 
      activo: 1, 
      deleted_at: null, 
      created_at: "2016-07-26 17:50:38", 
      updated_at: "2016-10-05 22:12:51", 
      carga_trabajo: 0 
    }

In theory, by correcting this, you should be able to do this without problems:

Object.keys($scope.tecnicos)

And I would return an arrangement with all the keys of the object:

['id_usuario', 'nombre', 'puesto', 'perfil_id', 'empresa_id', 'nombre_usuario', 'correo', 'activo', 'deleted_at', 'created_at', 'updated_at', 'carga_trabajo']

And if that's what you do .length :

$scope.count = Object.keys($scope.tecnicos).length;
console.log($scope.count); // console: 12

The result is 12

    
answered by 31.05.2017 в 19:52