3

我有一个这样的json数据:

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

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

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 的这种格式。

谢谢您的帮助。

4

1 回答 1

5

您的 JSON 示例完全没有意义,因为您通常会有一些数组来保存子节点。但这里有一个应该很容易适应不同结构的例子。有优化的空间,一些循环可以组合在一起以获得更高效的代码。我将所有内容分解为不同的循环,以使代码更易于理解。当然还有其他方法,但这是一种:

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);
于 2013-05-14T22:15:35.143 回答