データをツリー構造に保持する配列がありますが、このデータを json に変換したいと思います。これは私のデータの例です:
[Object]
0: Object
children: Array[1]
0: Object
children: Array[1]
0: Object
children: Array[10]
0: Object
children: Array[6]
value: Object
1: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
8: Object
9: Object
value: Object
Id: "00145E5BB2641EE284F811A7907757A3"
Parent: "00145E5BB2641EE284F811A7907737A3"
Ref: undefined
Text: "Functional Areas"
Type: "TWB"
ここで、これらのデータ配列を Json に変換したいと思います。JSON.stringify(myArray); を試しました。しかし、形式が正しくありません。ツリーのすべての構造を破壊します。何か案は?
これは、上記の結果を与えるコードです。
function transformToStruct(xmlData, callback) {
var data = xmlData.item;
var roots=[];
var children = {};
var arry=createStructure(data);
// find the top level nodes and hash the children based on parent
for (var i = 0, len = arry.length; i < len; ++i) {
var item = arry[i],
p = item.Parent,
target = [];
if(p == rootId) {
target = roots;
}
else {
target = (children[p] || (children[p] = []));
}
target.push({ value: item });
}
// function to recursively build the tree
var findChildren = function(parent) {
if (children[parent.value.Id]) {
parent.children = children[parent.value.Id];
for (var i = 0, len = parent.children.length; i < len; ++i) {
findChildren(parent.children[i]);
}
}
};
// enumerate through to handle the case where there are multiple roots
for (var i = 0, len = roots.length; i < len; ++i) {
findChildren(roots[i]);
}
// var returnV = JSON.stringify(roots);
// callback(returnV);
callback(roots)
}
function createStructure(data) {
var arry = [];
$.each(data, function(i, val) {
var parent = val["ParentId"]["#text"];
var id = val["NodeId"]["#text"];
var text = val["NodeText"]["#text"];
var level = val["NodeLevel"]["#text"];
var ref = val["RefObject"]["#text"];
var type = (val["NodeType"]["#text"]).substring(0,3);
if(level == "01")
rootId = parent;
var item = {"Id": id, "Text": text, "Parent": parent, "Type" : type, "Ref" : ref};
arry[i] = item;
// arry.push(item);
});
console.log(arry)
return arry;
}