简体   繁体   English

有没有办法直接在角度表达式中计算 json 对象中的键数?

[英]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.我需要在网页上显示 json 对象中的键数。 So, is there a way to calculate the count directly in the angular expression?那么,有没有办法直接在角度表达式中计算计数呢?

For example,例如,

JSON: JSON:

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

For this 'json', there are three keys.对于这个“json”,有三个键。 I want to get the count of keys directly in an angular expression without calculating it in the controller.我想直接在角度表达式中获取键的计数,而不在控制器中计算它。

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

Some hacky way would be to do the following:一些hacky方法是执行以下操作:

howManyKeys = {
    a: 'Do',
    b: 'I',
    c: 'have?',
}
  1. If you only want to use it a few times:如果您只想使用它几次:
This object has {{ (howManyKeys | keyValue).length }} keys
<span *ngIf="(howManyKeys | keyValue).length > 2">That's more than 2!</span>
  1. If you only want to show it on many spots:如果你只想在很多地方展示它:
<span *ngFor="let howManyKeysLength of [(howManyKeys | keyValue).length]">
   This object has {{howManyKeysLength}} keys.
   <span *ngIf="howManyKeysLength > 2">That's more than 2!</span>
   <span *ngIf="howManyKeysLength < 5">Less than 5!</span>
</span>

This can be useful when you don't want to add a service.当您不想添加服务时,这可能很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM