【发布时间】:2017-09-18 00:44:48
【问题描述】:
您将如何在没有父键或任何引用 id 但通过匹配 前缀 "- " 的 javascript 中从 json 数组构建树?
前缀在树的深度上递增。例如
"- " = level one
"- - " = level two
"- - - " = level three
...
有几个类似的问题,但尚未找到相关答案。
到目前为止,我已经做了如下的事情:
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>
上面sn-p的结果:
[
{ "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":[] }
]
预期结果:
[
{ "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":[] }
]
【问题讨论】:
-
没有像 JSON 数组 这样的东西。 JSON总是是一个字符串。
标签: javascript jquery arrays json recursion