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

Issue

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;
    }
})

Answered By – Tarun Dugar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published