我正在尝试使用 JSON 值来查看 ng-repeat 中的数据。但我只得到第一个值。我尝试使用其他方法但无法正确获取该值。
我的 JSON 响应:-
{
"stylesheet": {
"attribute-set": [
{
"attribute": {
"_name": "text-align",
"__prefix": "xsl",
"__text": "center"
},
"_name": "__frontmatter",
"__prefix": "xsl"
},
{
"attribute": [
{
"_name": "space-before",
"__prefix": "xsl",
"__text": "80mm"
},
{
"_name": "space-before.conditionality",
"__prefix": "xsl",
"__text": "retain"
},
{
"_name": "font-size",
"__prefix": "xsl",
"__text": "22pt"
},
{
"_name": "font-weight",
"__prefix": "xsl",
"__text": "bold"
},
{
"_name": "line-height",
"__prefix": "xsl",
"__text": "140%"
}
],
"_name": "__frontmatter__title",
"_use-attribute-sets": "common.title",
"__prefix": "xsl"
}
],
"_xmlns:xsl": "http://www.w3.org/1999/XSL/Transform",
"_xmlns:fo": "http://www.w3.org/1999/XSL/Format",
"_version": "2.0",
"__prefix": "xsl"
}
}
根据上一个问题的建议,我想从 "attribute"
键获取 "__name"
中的所有数据。
我按照我的 Controller 上的建议尝试了此操作:-
console.log($scope.jsonObj);
angular.forEach($scope.jsonObj,function(value,key){
console.log(value["attribute-set"][0]["attribute"]["_name"]);
});
jsonObj 是我的 JSON 对象
我的控制台中的输出是 text-align
,这是第一个 _name
属性值。
如何从此 JSON 实现 _name
值的 ng-repeat ?
最佳答案
数据结构相当糟糕,相同的对象键具有不同的数据类型,这使得事情有点困难。但是,这将返回所有 _name
字段的列表。
然后将其绑定(bind)到您的范围等。
data
.stylesheet['attribute-set']
.map(x => {
if (Array.isArray(x.attribute))
return x.attribute.map(y => y['_name']);
else
return [x.attribute['_name']];
})
.reduce((accu, cur) => accu.concat(...cur), []);
它本质上是将 _name
字段提取到每个属性集的数组中,然后将其缩减为单个数组。
查看实际效果 here
关于javascript - 无法迭代多个 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52199828/