Javascript Tree Lables / Levels

时间:2017-03-02 18:05:34

标签: javascript lodash

var myArray = [{
    title: "Title 1",
    children: [{
      title: "Title 1.1",
      children: [{
        title: "Title 1.1.1"
      }]
    }, {
      title: "Title 1.2",
      children: []
    }]
  },
  {
    title: "Title 2",
    children: [{
      title: "Title 2.1",
      children: [{
        title: "Title 2.1.1"
      }]
    }, {
      title: "Title 2.2",
      children: [{
        title: "Title 2.2.1"
      }]
    }]
  }
];

所以我有一个类似于此的数组。 标题是随机的,但我想得的是等级,例如

{ title: 'Title 2.2 (or any othe random title)', level: '2.2', children:[...]}

我希望这是递归的,并且非常感谢lodash解决方案。 感谢。

1 个答案:

答案 0 :(得分:1)

您可以使用迭代和递归方法。



function addLevel(array, levels) {
    levels = levels || [];
    array.forEach(function (o, i) {
        o.level = levels.concat(i + 1).join('.');
        if (Array.isArray(o.children)) {
            addLevel(o.children, levels.concat(i + 1));;
        }
    });
}

var myArray = [{ title: "Title 1", children: [{ title: "Title 1.1", children: [{ title: "Title 1.1.1" }] }, { title: "Title 1.2", children: [] }] }, { title: "Title 2", children: [{ title: "Title 2.1", children: [{ title: "Title 2.1.1" }] }, { title: "Title 2.2", children: [{ title: "Title 2.2.1" }] }] }];

addLevel(myArray);

console.log(myArray);

.as-console-wrapper { max-height: 100% !important; top: 0; }