Как построить древовидную структуру JSON, используя точечную запись объекта - PullRequest
1 голос
/ 13 января 2020

У меня есть коллекция строковых литералов в массиве

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

Как создать древовидную структуру ниже JSON, используя JavaScript? Любая помощь будет заметна.

[{
    "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"
        }
      ]
    }]
  }
]

1 Ответ

1 голос
/ 13 января 2020

Использование 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)
...