Search code examples
jsonangularjsangularjs-scope

Is there a way to count the number of keys in a json object directly in angular expressions?


I need to show the number of keys in a json object on a web page. So, is there a way to calculate the count directly in the angular expression?

For example,

JSON:

$scope.json = {"key1": "value1", "key2": "value2", key3: "value3"}

For this 'json', there are three keys. I want to get the count of keys directly in an angular expression without calculating it in the controller.


Solution

  • You would have to use a custom filter like this:

    template:

    {{json | numKeys}}
    

    filter:

    app.filter('numKeys', function() {
        return function(json) {
            var keys = Object.keys(json)
            return keys.length;
        }
    })