gpt4 book ai didi

javascript - Angular 应用程序读取不规则 json 的功能

转载 作者:行者123 更新时间:2023-12-02 17:26:18 25 4
gpt4 key购买 nike

我有一个 angularjs 应用程序,它从具有类似于以下结构的 json 读取数据:

[ { "name" : "TIER 1",
"children" : [
{ "children" : [ "ENGL-1301","HIST-1301"],
},
{ "children" : [ {"children" : [{ "course" : "SPCH 1311","term" : "Spring 2012"} ]}, "SPCH-1311","SPCH-1315","SPCH-1321"],
"name" : "Speaking and Listening",

},
{ "children" : [ "MATH-1314","MATH-1414","MATH-1316"],
"name" : "Quantitative Reasoning", "subcategory2" : [ ]
},
{ "children" : [ "ARTS-1311","ARTS-1312","ARTS-1313"],
"name" : "Wellness and The Human Experience","subcategory2" : [ ]
}
]
},
{ "name" : "TIER 2",
"children" : [
{ "children" : [ {"children" : [{ "course" : "ENGL 1302","term" : "Summer 2012"} ]}, "ENGL-1302" ],
"name" : "Qualitative Reasoning, Literacy and Research",
},
{ "children" : [ {"children" : [{ "course" : "GOVT 2301","term" : "Spring 2012"},
{ "course" : "PSYC 2301","term" : "Summer 2012"} ]}, "HIST-1302","HIST-2301","HIST-2328"],
"name2" : "Self and Society",
},
{ "children" : [ "ARTS-1301","ARTS-1303","ARTS-1304","DANC-2303"],
"name2" : "Humanity, Creativity and the Aesthetic Experience",
},
]
}
]

如您所见,json 文件看起来组织得不好。它有一些带有 children 的元素,这些 children 还有更多名为 children 的元素。因此,为了将此 json 文件读入 Angular 应用程序,我想定义一个名为 isemptychildren() 的函数来检查特定子元素是否有更多子类别。

如果问题变得令人困惑,我深表歉意,但我不知道更好的方法来解释它。我该如何编写这个函数?

最佳答案

适用于所有浏览器的稳健检查是对所有元素递归使用 Object.keys() 函数,例如:

function isEmptyChildren(hash){
return (Object.keys(hash).indexOf("chidren") == -1) ? true : false;
}

尽管为了您自己的理智着想,我建议您尽可能修改该数据结构,以使用不同的命名约定。

关于javascript - Angular 应用程序读取不规则 json 的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23480025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com