如何使用对象点表示法构建 JSON 树结构

How to build a JSON tree structure using object dot notation

我在数组中有一组字符串文字

var selected = ['a', 'b.c', 'b.c.d', 'b.c.d.e'];

如何使用 JavaScript 创建下面的 JSON 树结构?任何帮助将不胜感激。

[{
    "title": "a",
    "id": "a"
  },
  {
    "title": "b",
    "id": "b",
    "children": [{
      "title": "c",
      "id": "c",
      "children": [{
          "title": "d",
          "id": "d",
          "children": [{
            "title": "e",
            "id": "e"
          }]
        },
        {
          "title": "f",
          "id": "f"
        }
      ]
    }]
  }
]

使用recursion

var selected = ['a', 'b.c', 'b.c.d', 'b.c.d.e', 'b.c.g'];
var result = {};

selected.forEach(i =>
  i.split('.').reduce((result, val) => result[val] = result[val] || {}, result)
)

function toTree(o) {
  return Object.entries(o).map(([k, v]) => {
    let r = {'title': k, 'id': k, 'children': toTree(v)}
    !r.children.length && delete r.children
    return r
  })
}
result = toTree(result)

console.log(result)