如何在JavaScript中使用平面数据构建层次结构树? [英] How can I build a hierarchy tree from flat data in JavaScript?

查看:81
本文介绍了如何在JavaScript中使用平面数据构建层次结构树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的json数据:

I have a json data like this :

Data = [{"Id":"1", "Name":"abc", "Parent":""}, {"Id":"2", "Name":"abc", "Parent":"1"},
{"Id":"3", "Name":"abc", "Parent":"2"},{"Id":"4", "Name":"abc", "Parent":"2"}]

我想将这些数据转换为这样的层次结构树:

I want to transform this data into hierarchy tree like this :

root: {
        Id:"1",
        Name:"abc", 
        Parent:"",
        0: {
            Id:"2",
            Name:"abc",
            Parent:"1",
             0:{
                Id:"3",
                Name:"abc",
                Parent:"2",
             1:{
                Id:"4",
                Name:"adb",
                Parent:"2",
.....
}

目前我有想法只使它成为数组对象,但该格式对我不起作用。因为我需要在sapui5中使用TreeTable的这种格式。

Currently I have the idea only make it as the array object but that format won't work for me. Because I need this format for TreeTable in sapui5.

感谢您的帮助。

推荐答案

您的JSON示例确实如此完全没有意义,因为你通常会有一些数组来保存子节点。但这是一个应该很容易适应不同结构的例子。存在优化空间,并且可以将一些循环组合在一起以获得稍微更高效的代码。我把所有的东西都打破了不同的循环,使代码更容易理解。当然还有其他方法,但这是一个:

Your JSON example does not make sense completely, as you generally would have some array to hold the child nodes. But here's an example that should be easy to adapt to different structures. There is room for optimization, and some of the loops could be combined together for slightly more efficient code. I broke all the things to different loops to make the code more understandable. For sure there are other approaches, but this is one:

var data = [{"Id":"1", "Name":"abc", "Parent":""}, {"Id":"2", "Name":"abc", "Parent":"1"}, {"Id":"3", "Name":"abc", "Parent":"2"},{"Id":"4", "Name":"abc", "Parent":"2"}];

// flatten to object with string keys that can be easily referenced later
var flat = {};
for (var i = 0; i < data.length; i++) {
  var key = 'id' + data[i].Id;
  flat[key] = data[i];
}

// add child container array to each node
for (var i in flat) {
  flat[i].children = []; // add children container
}

// populate the child container arrays
for (var i in flat) {
  var parentkey = 'id' + flat[i].Parent;
  if (flat[parentkey]) {
    flat[parentkey].children.push(flat[i]);
  }
}

// find the root nodes (no parent found) and create the hierarchy tree from them
var root = [];
for (var i in flat) {
  var parentkey = 'id' + flat[i].Parent;
  if (!flat[parentkey]) {
      root.push(flat[i]);
  }
}

// here it is!
window.console.log(root);

这篇关于如何在JavaScript中使用平面数据构建层次结构树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆