Search code examples
javascriptangularjsangularjs-scope

How to count total and null values in AngularJs object


I'm trying to count total not null fields out of total fields in my angularjs object, then I want to calculate the percentage.

eg:

in my object contain 10 fields.two fields have some values(others null).

Completed = (not null fields/total fields)*100 = (4/11)*100 = 36.36%

my controller

myApp.controller('PController', function ($scope,localStorageService) {

$scope.user = localStorageService.get("user");

console.log(Object.keys($scope.user).length);
});

now i can get total fields.but how can i count not null fields and callculate percentage?

$scope.user object is like below

{
    "user_id": "205",
    "first_name": null,
    "last_name": null,
    "email": "at@yuib.com",
    "address": null,
    "mobile": null,
    "phone": null,
    "profile_img": null,
    "gender": null,
    "registered": "1",
    "addresses": 0
}

Solution

  • simple filter method with Object.keys on the $scope.user should give the required result

    Object.keys($scope.user).filter(x=>$scope.user[x]!==null).length