从嵌套的集合模型javascript创建JSON [英] Create JSON from nested set model javascript
本文介绍了从嵌套的集合模型javascript创建JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个数据结构,显示嵌套树中每个节点的深度:
I have this data structure that show the depth of each node in the nested tree:
[
{
"name": "ELECTRONICS",
"depth": 0
},
{
"name": "TELEVISIONS",
"depth": 1
},
{
"name": "TUBE",
"depth": 2
},
{
"name": "PLASMA",
"depth": 2
},
{
"name": "GAME CONSOLES",
"depth": 1
},
{
"name": "MP3 PLAYERS",
"depth": 1
},
{
"name": "FLASH",
"depth": 2
}]
我想将使用JavaScript / node.js / Angular的预览数据转换为这样的分层JSON:
I would like to transform the previews data with JavaScript / node.js / Angular into a hierarchical JSON like this:
[{
"name": "ELECTRONICS",
"children": [
{
"name": "TELEVISIONS",
"children": [
{
"name": "TUBE"
},
{
"name": "PLASMA"
}]
},
{
"name": "GAME CONSOLES"
},
{
"name": "MP3 PLAYERS",
"children": [
{
"name": "FLASH"
}]
}]
}]
推荐答案
你可以使用 数组#forEach
和一个用于深度参考的数组。
You could use Array#forEach
and an array for the reference to the depth.
var data = [{ "name": "ELECTRONICS", "depth": 0 }, { "name": "TELEVISIONS", "depth": 1 }, { "name": "TUBE", "depth": 2 }, { "name": "PLASMA", "depth": 2 }, { "name": "GAME CONSOLES", "depth": 1 }, { "name": "MP3 PLAYERS", "depth": 1 }, { "name": "FLASH", "depth": 2 }],
tree = [];
data.forEach(function (a, i, aa) {
var lastDepth = (aa[i - 1] || {}).depth, o;
if (a.depth !== 0 && a.depth > lastDepth) {
o = this[lastDepth][this[lastDepth].length - 1]
o.children = o.children || [];
this[a.depth] = o.children;
}
this[a.depth].push({ name: a.name });
}, [tree]);
console.log(tree);
这篇关于从嵌套的集合模型javascript创建JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文