Create JSON from nested set model javascript

2020-07-18 07:24发布

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
  }]

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"
         }]
    }]
}]

3条回答
成全新的幸福
2楼-- · 2020-07-18 07:26

Here's the magic

var json = [
  {
    "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
  }];

var newJSON = [];
function createTree(parentID, i, node, depth)
{
  node.children = [];
  delete node.depth;
  while (i < json.length && json[i].depth > parentID)
  {
    if (depth === json[i].depth)
    {
        node.children.push(json[i]);
    }
    else
    {
      createTree(json[i-1].depth, i, json[i-1], depth + 1);
    }
    i++;
  }
  if (node.children.length === 0)
  {
    delete node.children;
  }
  return node;
}

var parent = {};
parent = createTree(-1, 0, parent, 0);
console.log(parent.children);
JSON.stringify(parent.children);

I've assumed that if the depth of the next array element is equal it's a sibling, if it's minor it's a children and if it's bigger we don't have to add any more elements to this branch. So, I create a branch, if it's the same depth i add it to our parent, if depth is less, i create a new branch and if it's bigger i stop creating branches and adding children to "my" parent.

EDIT

I'd pick Nina Scholz's solution because it's easier to understand

查看更多
对你真心纯属浪费
3楼-- · 2020-07-18 07:33

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);

查看更多
欢心
4楼-- · 2020-07-18 07:33

This may help

// Code goes here

angular.module("app",[])
.controller("ctrl", function($scope, $log){
   
   $scope.src = [
  {
    "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
  }];
  
  $scope.tree  = _.findWhere($scope.src, {"depth":0});
    
function makeTree(parentNode){
    var d = parentNode.depth  +1;    
    var children = _.where($scope.src, {"depth" : parentNode.depth+1});

    if(children!=null){
      parentNode.children = children;
      parentNode.children.forEach(function(c){
        makeTree(c);
      });


    }
  }

  makeTree($scope.tree);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script data-require="underscore.js@1.5.2" data-semver="1.5.2" src="//cdn.jsdelivr.net/underscorejs/1.5.2/underscore-min.js"></script>
    
<body ng-app="app">
    
    <div ng-controller="ctrl">

        First Node : {{firstNode|json}}
              <h1>tree</h1>
      <pre>{{tree|json}}</pre>
    </div>
  </body>

查看更多
登录 后发表回答