我有这个数据结构显示嵌套树中每个 Node 的深度:
[
{
"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:
[{
"name": "ELECTRONICS",
"children": [
{
"name": "TELEVISIONS",
"children": [
{
"name": "TUBE"
},
{
"name": "PLASMA"
}]
},
{
"name": "GAME CONSOLES"
},
{
"name": "MP3 PLAYERS",
"children": [
{
"name": "FLASH"
}]
}]
}]
最佳答案
你可以使用 Array#forEach
以及一个用于引用深度的数组。
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 - 从嵌套集模型 javascript 创建 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38512301/