寻求帮助,从字符串生成嵌套对象树。
示例1
A > B > C
应该导致对象:
{
name: A,
children: [{
name: B,
children: [{
name: C
}],
}]
}
示例2
A > B > C | A > D > E
对象中的结果:
{
name: A,
children: [{
name: B,
children: [{
name: C
},{
name: D,
children: [{
name: E
}],
}],
}]
}
到目前为止我有什么:
问题是,我不确定如何正确解决嵌套问题。
let categoryTree = {
categories: [{}]
}
const split = (string, seperator = '|', splitter = ' > ') => {
if (!string.includes(seperator)) {
let results = string.split(splitter)
for (let i = 0; i < results.length; i++) {
let lastNode = 0
if (i != 0) {
lastNode = i - 1
}
makeTree(results[i], results[lastNode], i)
}
}
console.log(categoryTree)
return categoryTree
}
const makeTree = (item, parent, i) => {
if (categoryTree.categories[parent].name === item && categoryTree.categories[parent].name) {
console.log('IN')
categoryTree.categories[parent].categories.push({
name: item,
categories: [{}]
})
} else {
categoryTree.categories.push({name: item, categories: []})
}
}
答案 0 :(得分:3)
您可以使用迭代和递归方法,将对象作为项目的参考。
var result = [],
string = 'A > B > C | A > D > E';
string.split(' | ').forEach(function (a) {
var keys = a.split(' > '),
last = keys.pop();
keys.reduce(function (r, k) {
if (!r[k]) {
r[k] = { _: [] };
r._.push({ name: k, children: r[k]._ });
}
return r[k];
}, this)._.push({ name: last });
}, { _: result });
console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;