我正在尝试整理一些 json 数据。如果我使用我的测试数据,如以下一切正常!
var data = [
{ "title": 1, "parentids": [0] },
{ "title": 2, "parentids": [1] },
{ "title": 3, "parentids": [1] },
{ "title": 4, "parentids": [2, 3] },
];
因此,如果我对这个数据集使用我的函数,我会收到以下结构,这实际上就是我想要的。
[
{
"title": 0,
"parentids": [],
"children": [
{
"title": 1,
"parentids": [
0
],
"children": [
{
"title": 2,
"parentids": [
1
],
"children": [
{
"title": 4,
"parentids": [
2,
3
],
"children": []
}
]
},
{
"title": 3,
"parentids": [
1
],
"children": [
{
"title": 4,
"parentids": [
2,
3
],
"children": []
}
]
}
]
}
]
}
]
但!我的数据发生了变化。不幸的是,我的头衔和父代现在是字符串值
var data = [
{ "title": "any", "parentids": [""] },
{ "title": "culture", "parentids": ["any"] },
{ "title": "building", "parentids": ["any"] },
{ "title": "museum", "parentids": ["culture", "building"] },
];
我真的尝试了很多来更改和编辑我现有的代码,但它不会工作......要么没有输出,要么层次结构不像预期的那样。这是我的实际函数,适用于第一个数据集。我怎么能改变它,它适用于字符串父代;
function unflatten(arr) {
var node,
graph = [],
mapped = [];
// First map the nodes of the array to an object
for (var i = 0, len = arr.length; i < len; i++) {
node = arr[i];
mapped[node.title] = node;
mapped[node.title]['children'] = [];
}
// 2. assign children:
mapped.forEach(function (node) {
// Add as child to each of the parents
node.parentids.forEach(function (parentid) {
if (mapped[parentid]) {
mapped[parentid]['children'].push(node);
} else {
// If parent does not exist as node, create it at the root level,
// and add it to first level elements array.
graph.push(mapped[parentid] = {
title: parentid, //name in this case its 0
parentids: [],
children: [node]
});
}
});
});
return graph;
};
var graph = unflatten(types);
console.log(JSON.stringify(graph, null, 4));
document.body.innerHTML = "<pre>" + (JSON.stringify(graph, null, " "))
我不确定,但我认为带有“if(mapped [parentid]”)的第二部分会导致问题?因为我现在使用的是字符串而不是整数?我真的不知道如何继续......我很感激任何提示或解决方案! 提前致谢,祝您度过愉快的一天/一周