我试图找出将一些 JSON 数据转换为bootstrap-treeview请求的格式的最佳方法。我最初的想法是创建某种递归函数来遍历和修改所有内容,但我在实现这一点时遇到了一些真正的困难。任何建议将不胜感激!
这是我的服务返回的数据的控制台日志:
Object
England: Object
London: Object
Bayerische Staatsbibliothek: Object
Cod. arab. 1251: Array[1]
0: Object
key1: "adflkjadf",
key2: "adflkjadfk",
key3: "adlkfjadf",
__proto__: Object
length: 1
text: "Cod. arab. 1251"
__proto__: Array[0]
Cod. arab. 1252: Array[1]
Cod. arab. 1253: Array[1]
Cod. arab. 1254: Array[1]
Cod. arab. 1255: Array[1]
Cod. arab. 1256: Array[1]
Cod. arab. 1257: Array[1]
Cod. arab. 1258: Array[1]
Cod. arab. 1259: Array[1]
Cod. arab. 1260: Array[1]
Germany: Object
Munich: Object
Bayerische Staatsbibliothek: Object
Cod. arab. 1251: Array[1]
0: Object
key1: "adflkjadf",
key2: "adflkjadfk",
key3: "adlkfjadf",
__proto__: Object
length: 1
text: "Cod. arab. 1251"
__proto__: Array[0]
Cod. arab. 1252: Array[1]
Cod. arab. 1253: Array[1]
Cod. arab. 1254: Array[1]
Cod. arab. 1255: Array[1]
Cod. arab. 1256: Array[1]
Cod. arab. 1257: Array[1]
Cod. arab. 1258: Array[1]
Cod. arab. 1259: Array[1]
Cod. arab. 1260: Array[1]
这是 boostrap-treeview 需要的格式:
var tree = [
{
text: "Parent 1",
nodes: [
{
text: "Child 1",
nodes: [
{
text: "Grandchild 1"
},
{
text: "Grandchild 2"
}
]
},
{
text: "Child 2"
}
]
},
{
text: "Parent 2"
},
{
text: "Parent 3"
},
{
text: "Parent 4"
},
{
text: "Parent 5"
}
];
这是我尝试使用递归函数来完成此操作:
function format_for_treeview(node) {
for (var key in node) {
// skip loop if the property is from prototype
if (!node.hasOwnProperty(key)) continue;
if (typeof node === 'object') {
format_for_treeview(node[key]);
if (Array.isArray(node)) {
node[key]['text'] = node[key]['bibliography_text'];
} else {
node[key]['text'] = key;
}
}
}
}