【发布时间】:2018-01-16 15:26:14
【问题描述】:
我有一些存储在嵌套 JSON 中的名称数组,如下所示:
{
"groupZ": {
"names": [
"Steve",
"Henry"
]
},
"groupY": {
"groupA": {
"names": [
"Laura"
]
},
"groupB": {
"names": [
"Alice",
"Bob",
"Neil"
]
}
},
"groupX": {
"groupC": {
"groupD": {
"names": [
"Steph"
]
}
},
"groupE": {
"names": [
"Aaron",
"Dave"
]
}
}
}
我试图弄清楚如何生成所有名称的列表,并在每个名称前面加上完整的组路径,所以它最终是这样的:
- groupZ - 史蒂夫
- groupZ - 亨利
- groupY - groupA - 劳拉
- groupY - groupB - Alice
- groupY - groupB - Bob
- groupY - groupB - 尼尔
- groupX - groupC - groupD - Steph
- groupX - groupE - Aaron
- groupX - groupE - 戴夫
组名在每个级别都是唯一的,但除此之外可以称为任何名称。我知道我将需要递归调用一个函数,该函数在找到“名称”数组时停止,通过一个字符串添加到每个递归的前置,但遇到了真正的麻烦。到目前为止,这是我的代码:
var sPrepend = '';
function buildList(Groups, lastGroupName){
for(var thisGroupName in Groups) {
var thisGroup = Groups[thisGroupName];
if(!thisGroup.names){
sPrepend += (' - ' + thisGroupName);
buildList(thisGroup, thisGroupName);
}
if(thisGroup.names){
thisGroup.names.forEach(function(name){
console.log(sPrepend, ' - ', name);
//build the list item here.
});
}
}
}
buildList(oGroups, '');
这让我很困惑,因为我无法更改 JSON 结构,但我确信这是可能的。感谢任何可以提供帮助的人!
【问题讨论】:
标签: javascript arrays json javascript-objects nested-loops