通过javascript将json转换为树数据
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过javascript将json转换为树数据相关的知识,希望对你有一定的参考价值。
我有这种数据。
[
"dbname": "db1",
"tblname": "tbl1",
"colname": "ID_1",
"RowCounts": "50"
,
"dbname": "db1",
"tblname": "tbl1",
"colname": "ID_2",
"RowCounts": "50"
,
"dbname": "db1",
"tblname": "tbl1",
"colname": "ID_3",
"RowCounts": "50"
,
"dbname": "db1",
"tblname": "tbl1",
"colname": "ID_4",
"RowCounts": "30"
,
"dbname": "db1",
"tblname": "tbl2",
"colname": "ID_1",
"RowCounts": "20"
,
"dbname": "db1",
"tblname": "tbl2",
"colname": "ID_2",
"RowCounts": "30"
,
"dbname": "db1",
"tblname": "tbl2",
"colname": "ID_3",
"RowCounts": "10"
,
"dbname": "db1",
"tblname": "tbl2",
"colname": "ID_4",
"RowCounts": "60"
,
"dbname": "db1",
"tblname": "tbl2",
"colname": "ID_5",
"RowCounts": "30"
,
"dbname": "db1",
"tblname": "tbl3",
"colname": "ID_6",
"RowCounts": "20"
]
而且我想转换成这种格式。
["name":"db1",
"rowcount":500, //sum of child row counts
"children":[
"name":"tbl1",
"rowcount":200, //sum of children row counts
"children":[
"name":"ID_1",
"rowcount":50
,
"name":"ID_2",
"rowcount":50
],
"name":"tbl2",
"rowcount":200,
"children":[
]]]
我该怎么做?我尝试过此方法,但没有用。
我导入了csv文件,但其结构无法与树形结构配合使用,因此我需要对其进行转换。它具有3个字段,即dbname,tblname,colname和行数。只需将行计数视为价值或其他东西即可。只是需要合并。
function createTreeData(structure) const node = (name, parent = null, row_cnt = 0) => ( name, parent, row_cnt, children: [] ); const addNode = (parent, child) => (parent.children.push(child), child); const findNamed = (name, parent) => for (const child of parent.children) if (child.name === name) return child const found = findNamed(name, child); if (found) return found const TOP_NAME = "Top", top = node(TOP_NAME); for (const children of structure) let par = top; for (const name of children) const found = findNamed(name, par); par = found ? found : addNode(par, node(name, par.name)); return top;
它创建树结构,但不创建行数,并将其子级的行数相加。
任何帮助将不胜感激。
我有这种数据。 [“” dbname“:” db1“,” tblname“:” tbl1“,” colname“:” ID_1“,” RowCounts“:” 50“,” dbname“:” db1“,” tblname“:.. 。
答案
您可以使用一组用于嵌套结构的键,减少此结构,并向最内部的数组添加一个新对象。在途中添加行数。
以上是关于通过javascript将json转换为树数据的主要内容,如果未能解决你的问题,请参考以下文章
将具有多个字段的表单数据转换为 JSON Jquery Javascript
如何将 csv 转换为 json 并编写特定函数以使用 javascript 生成图形?
怎样将JAVA中得list集合转换为javascript的二维数组?