How would you build tree from a json array in javascript with no parent key or any reference id but by matching a prefix "- "?
The prefix is incremental upon the depth of tree. for e.g.
"- " = level one
"- - " = level two
"- - - " = level three
...
There are a few similar questions but no relevant answer has been found yet.
So far, I have done something like below:
var $json = [
{ "id":"11", "text":"CatOne" },
{ "id":"12", "text":"- CatOneSubCat1" },
{ "id":"13", "text":"- CatOneSubCat2" },
{ "id":"14", "text":"- - CatOneSubCat2SubCat1" },
{ "id":"15", "text":"- - CatOneSubCat2SubCat2" },
{ "id":"16", "text":"- CatOneSubCat3" },
{ "id":"17", "text":"CatTwo" },
{ "id":"18", "text":"CatThree" },
{ "id":"19", "text":"CatFour" },
{ "id":"20", "text":"- CatFourSubCat1" },
{ "id":"21", "text":"- CatFourSubCat2" },
{ "id":"22", "text":"CatFive" }
];
$(document).ready(function(){
var $arr = [];
var $str = "";
var $prefix = "- ";
$.each( $json, function( key, value ) {
value.children = [];
// TODO: additional prefix should be appended upon the depth of tree
if(!value.text.startsWith($prefix)) {
$arr.push(value);
}
else {
$arr[$arr.length - 1].children.push(value);
}
});
$("#mypre").text(JSON.stringify($arr, null, 2));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="mypre"></pre>
Result from the snippet above:
[
{ "id":"11", "text":"CatOne", "children":[
{ "id":"12", "text":"- CatOneSubCat1", "children":[] },
{ "id":"13", "text":"- CatOneSubCat2", "children":[] },
{ "id":"14", "text":"- - CatOneSubCat2SubCat1", "children":[] },
{ "id":"15", "text":"- - CatOneSubCat2SubCat2", "children":[] },
{ "id":"16", "text":"- CatOneSubCat3", "children":[] }
] },
{ "id":"17", "text":"CatTwo", "children":[] },
{ "id":"18", "text":"CatThree", "children":[] },
{ "id":"19", "text":"CatFour", "children":[
{"id":"20", "text":"- CatFourSubCat1", "children":[] },
{"id":"21", "text":"- CatFourSubCat2", "children":[] }
] },
{ "id":"22", "text":"CatFive", "children":[] }
]
Expected result:
[
{ "id":"11", "text":"CatOne", "children":[
{ "id":"12", "text":"- CatOneSubCat1", "children":[] },
{ "id":"13", "text":"- CatOneSubCat2", "children":[
{ "id":"14", "text":"- - CatOneSubCat2SubCat1", "children":[] },
{ "id":"15", "text":"- - CatOneSubCat2SubCat2", "children":[] }
]},
{ "id":"16", "text":"- CatOneSubCat3", "children":[] }
] },
{ "id":"17", "text":"CatTwo", "children":[] },
{ "id":"18", "text":"CatThree", "children":[] },
{ "id":"19", "text":"CatFour", "children":[
{ "id":"20", "text":"- CatFourSubCat1", "children":[] },
{ "id":"21", "text":"- CatFourSubCat2", "children":[] },
] },
{ "id":"22", "text":"CatFive", "children":[] }
]