Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

javascript - How to convert flat multi-branch data to hierarchical JSON?

[
  {
    "id": "a",
    "pid": "a",
    "name": "AA",
  },
  {
    "id": "b",
    "pid": "a",
    "name": "BB",
  },
  {
    "id": "c",
    "pid": "a",
    "name": "CC",
  },
  {
    "id": "x",
    "pid": "b",
    "name": "XX",
  }
]

Above is the data I got from the database. Every person has an id and a pid, pid points to the person's higher level person's id. If a person has highest level, the id equals pid.

I want to convert the raw data to hierarchical JSON, like this:

[
  {
    "id": "a",
    "name": "AA",
    "child": [
      {
        "id": "b",
        "name": "BB"
        "child": [
          {
            "id": "x",
            "name": "XX"
          }
        ]
      },
      {
        "id": "c",
        "name": "CC"
      }
    ]  
  }
]

I'm using Node.js.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I suggest you to create a tree and take id === pid as a root for the tree, which works for unsorted data.

How it works:

Basically, for every object in the array, it takes the id for building a new object as parentid for a new object.

For example:

{ "id": 6, "pid": 4 }

It generates this property first with id:

"6": {
    "id": 6,
    "pid": 4
}

and then with pid:

"4": {
    "children": [
        {
            "id": 6,
            "pid": 4
        }
    ]
},

and while all objects are similarly treated, we finally get a tree.

If id === pid, the root node is found. This is the object for the later return.

var data = [
        { "id": "f", "pid": "b", "name": "F" },
        { "id": "e", "pid": "c", "name": "E" },
        { "id": "d", "pid": "c", "name": "D" },
        { "id": "c", "pid": "b", "name": "C" },
        { "id": "a", "pid": "a", "name": "A" },
        { "id": "b", "pid": "a", "name": "B" }
    ],
    tree = function (data) {
        var r, o = Object.create(null);
        data.forEach(function (a) {
            a.children = o[a.id] && o[a.id].children;
            o[a.id] = a;
            if (a.id === a.pid) {
                r = a;
            } else {
                o[a.pid] = o[a.pid] || {};
                o[a.pid].children = o[a.pid].children || [];
                o[a.pid].children.push(a);
            }
        });
        return r;
    }(data);

console.log(tree);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...