栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将平面JSON文件转换为分层的json数据,例如flare.json [d3示例文件]

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将平面JSON文件转换为分层的json数据,例如flare.json [d3示例文件]

更新为使用递归方法

这应该适用于

n
级别,而不只是2或3。您只需要指定哪些属性定义哪些级别即可。

var data = [    { "dep": "First Top", "name": "First child", "model": "value1", "size": "320" },    { "dep": "First Top", "name": "First child", "model": "value2", "size": "320" },    { "dep": "First Top", "name": "SECOND CHILD", "model": "value1", "size": "320" },    { "dep": "Second Top", "name": "First Child", "model": "value1", "size": "320" }];var newData = { name :"root", children : [] },    levels = ["dep","name"];// For each data row, loop through the expected levels traversing the output treedata.forEach(function(d){    // Keep this as a reference to the current level    var depthCursor = newData.children;    // Go down one level at a time    levels.forEach(function( property, depth ){        // Look to see if a branch has already been created        var index;        depthCursor.forEach(function(child,i){ if ( d[property] == child.name ) index = i;        });        // Add a branch if it isn't there        if ( isNaN(index) ) { depthCursor.push({ name : d[property], children : []}); index = depthCursor.length - 1;        }        // Now reference the new child array as we go deeper into the tree        depthCursor = depthCursor[index].children;        // This is a leaf, so add the last element to the specified branch        if ( depth === levels.length - 1 ) depthCursor.push({ name : d.model, size : d.size });    });});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/437102.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号