Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to convert an array tree to Json tree?
    primarykey
    data
    text
    <p>I have an array that keep the data in tree structure but I'd like to transform this data to json. This is the example of my data :</p> <pre><code>[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" </code></pre> <p>Now I want to transform these array of data to Json. I tried JSON.stringify(myArray); but the format isn't correct. It destroys all structure of tree. Any ideas?</p> <p>This is the code that give the result above.</p> <pre><code>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 &lt; 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 &lt; 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 &lt; 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; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload