[英]How to build a JSON tree structure using object dot notation
I have a collection of string literals in an array我有一个数组中的字符串文字集合
var selected = ['a', 'b.c', 'b.c.d', 'b.c.d.e'];
How can I create a below JSON tree structure using JavaScript?如何使用 JavaScript 创建以下 JSON 树结构? Any help would be appreciable.
任何帮助将是可观的。
[{
"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"
}
]
}]
}
]
Using recursion
使用
recursion
var selected = ['a', 'b.c', 'bcd', 'bcde', 'bcg']; 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.