Javascript - 从平面数组

时间:2015-11-17 18:05:00

标签: javascript arrays treeview

我有一个员工列表,我从服务器端通过AJAX请求获得,此列表中的每个项目都是它下面项目的父项,除了最后一个孩子,所以在客户端,我最终得到一个像这样的JavaScript数组:

data = [
{ FirstName: "John", LastName: "Doe", Position: "Manager", ID: "5656" },
{ FirstName: "Sam", LastName: "Doe", Position: "Sale", ID: "654654" },
{ FirstName: "Sarah", LastName: "Doe", Position: "Employee", ID: "6541" },
{ FirstName: "Sally", LastName: "Doe", Position: "Clerk", ID: "8754" },
{ FirstName: "Joe", LastName: "Doe", Position: "Clerk", ID: "654564" }
];

到目前为止一直很好,现在我的问题是我想使用bootstrap-treeview,这个组件需要一个像这样的JavaScript数组:

var tree = [
  {
      text: "John - Manager",
      nodes: [
        {
            text: "Sam - Sale",
            nodes: [
              {
                  text: "Sarah - Employee",
                  nodes: [
                      {
                          text: "Sally - Clerk",
                          nodes: [
                              {
                                  text: "Joe - Clerk"
                              }
                          ]
                      }
                  ]
              }
            ]
        }
      ]
  }
];

我的树不是静态的,所以我必须动态生成它,如何使用JavaScript动态生成这样的无限嵌套数组?

1 个答案:

答案 0 :(得分:2)

此提案包含Array.prototype.reduceRight()

  

reduceRight()方法对累加器应用函数,并且数组的每个值(从右到左)必须将其减少为单个值。



var data = [
        { FirstName: "John", LastName: "Doe", Position: "Manager", ID: "5656" },
        { FirstName: "Sam", LastName: "Doe", Position: "Sale", ID: "654654" },
        { FirstName: "Sarah", LastName: "Doe", Position: "Employee", ID: "6541" },
        { FirstName: "Sally", LastName: "Doe", Position: "Clerk", ID: "8754" },
        { FirstName: "Joe", LastName: "Doe", Position: "Clerk", ID: "654564" }
    ],
    tree = data.reduceRight(function (r, a) {
        var o = { text: a.FirstName + ' - ' + a.Position };
        if (r) {
            o.nodes = r;
        }
        return [o];
    }, undefined);

document.write('<pre>' + JSON.stringify(tree, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

或使用Array.prototype.reduce()

  

reduce()方法对累加器和数组的每个值(从左到右)应用函数以将其减少为单个值。

&#13;
&#13;
var data = [
        { FirstName: "John", LastName: "Doe", Position: "Manager", ID: "5656" },
        { FirstName: "Sam", LastName: "Doe", Position: "Sale", ID: "654654" },
        { FirstName: "Sarah", LastName: "Doe", Position: "Employee", ID: "6541" },
        { FirstName: "Sally", LastName: "Doe", Position: "Clerk", ID: "8754" },
        { FirstName: "Joe", LastName: "Doe", Position: "Clerk", ID: "654564" }
    ], tree = [];

data.reduce(function (r, a) {
    var o = { text: a.FirstName + ' - ' + a.Position, nodes: [] };
    r.push(o);
    return o.nodes;
}, tree);

document.write('<pre>' + JSON.stringify(tree, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

两个提案之间的区别在于第一种情况是从最后一行迭代和构建数组/对象,并且返回始终是完整的树。

第二个提议以给定数组为特征,并返回对包含的行/节点的引用。建筑方案是从第一行到最后一行,与第一个提案相反。

第二种解决方案的缺点是空数组nodes