javascript - 从嵌套集模型 javascript 创建 JSON

标签 javascript angularjs json node.js

我有这个数据结构显示嵌套树中每个 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/

相关文章:

javascript - 用jQuery、正则表达式替换href

javascript - Angular - 将 ng Strict 与 Google Chart 库一起使用

javascript - Google MAP 区域坐标和多边形

javascript - 检索以 JSON 存储的特定数据

javascript - json嵌套查找在javascript中使用基于字符串的键

javascript - 如何通过模态表单创建关联表记录?

javascript - for in循环遍历数组但不遍历JS函数

javascript - 谷歌地图 - 如何为函数 initMap 添加参数?

javascript - 如何在 angularJS 中使用 $document 服务?

javascript - 将 JavaScript 对象(数组)转换为 XML