我有一个像这样的数组
[
"parent1|child1|subChild1","parent1|child1|subChild2","parent|child2|subChild1","parent1|child2|subChild2","parent2|child1|subChild1","parent2|child1|subChild2","parent2|child2|subChild1",.
.
.
]
在我的第一个字符串之前|是父项,|之前的第二个字符串是孩子,第二个字符串之后的第三个字符串|是子孩子
如何将该数组转换为类似对象
[
{
"id": "parent1","children":[
{
"id": "child1","children":[
{
"id": "subChild1"
}
]
}
]
}
]
父->子->子子对象
基于塞巴斯蒂安的答案,我在下面使用打字稿尝试了
private genTree(row) {
let self = this;
if (!row) {
return;
}
const [parent,...children] = row.split('|');
if (!children || children.length === 0) {
return [{
id: parent,children: []
}];
}
return [{
id: parent,children: self.genTree(children.join('|'))
}];
}
private mergeDeep(children) {
let self = this;
const res = children.reduce((result,curr) => {
const entry = curr;
const existing = result.find((e) => e.id === entry.id);
if (existing) {
existing.children = [].concat(existing.children,entry.children);
} else {
result.push(entry);
}
return result;
},[]);
for (let i = 0; i < res.length; i++) {
const entry = res[i];
if (entry.children && entry.children.length > 0) {
entry.children = self.mergeDeep(entry.children);
}
};
return res;
}
private constructTree(statKeyNames){
let self = this;
const res = this.mergeDeep(statKeyNames.map(self.genTree).map(([e]) => e));
console.log(res);
}
但这给了我“无法读取未定义的属性'genTree'”错误
更新:
根据塞巴斯蒂安的评论,将self.genTree更改为this.genTree.bind(this),并且没有任何问题