AngularJS:如何获取 JSON 对象的键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15525685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:49:01  来源:igfitidea点击:

AngularJS: How to get the key of a JSON Object

jsonangularjs

提问by callmekatootie

I am unsure if this has got anything to do with AngularJS at all and if it is only JSON related.

我不确定这是否与 AngularJS 有任何关系,是否仅与 JSON 相关。

Anyhow, let us say that we have the following JSON:

无论如何,让我们说我们有以下 JSON:

$scope.dataSets = {
    "names": ["Horace", "Slughorn", "Severus", "Snape"],
    "genders": ["Male", "Female"]
}

Now, I am using the ng-repeat directive to print the above as follows:

现在,我使用 ng-repeat 指令打印上述内容,如下所示:

<div ng-repeat="data in dataSets>
    //Continue readig to know what I am expcting here
</div>

What I expect within the <div></div>tags is to print "name" and "genders". That is, I wish to print the keys of the JSON. I have no idea what the keys are, as in they could be anything. How can I do this?

我期望在<div></div>标签中打印“姓名”和“性别”。也就是说,我希望打印 JSON 的键。我不知道密钥是什么,因为它们可以是任何东西。我怎样才能做到这一点?

回答by Stewie

As docs state it:

正如文档所说:

(key, value) in expression – where key and value can be any user defined identifiers, and expression is the scope expression giving the collection to enumerate.

(key, value) in expression – 其中 key 和 value 可以是任何用户定义的标识符,而 expression 是给出要枚举的集合的范围表达式。

<div ng-repeat="(key, data) in dataSets">
  {{key}}
</div>

回答by Saifudheen Aroniyil

for accessing Jsonkey-value pair from inside controller in AngularJs.

用于从AngularJs 中的控制器内部访问Json键值对。

for(var keyName in $scope.dataSets){        
     var key=keyName ;
     var value= $scope.dataSets[keyName ];

  alert(key)
  alert(JSON.stringify(value));

}

回答by edgarpetrauskas

if dataSets is an array and not an object you first need to ng-repeat the array items and then the key or value.

如果 dataSets 是一个数组而不是一个对象,您首先需要重复数组项,然后重复键或值。

<div ng-repeat="item in dataSets">
   <div ng-repeat="(key, value) in item">
   {{key}}
   {{value}}
   </div>
</div>

just my 2 cents.

只是我的 2 美分。

回答by Jose Ramon Polo

For every dataSet in dataSets, print the key and then iterate through the individual items:

对于 dataSets 中的每个数据集,打印键,然后遍历各个项目:

<div ng-repeat="(key, dataSet) in dataSets">
   <div>{{key}}</div>
   <div ng-repeat="value in dataSet">   
        {{value}}
   </div>
</div>

{{dataset}} can be displayed in one go also, the array would be displayed as a comma separated list of values.

{{dataset}} 也可以一次性显示,数组将显示为逗号分隔的值列表。