如何在Javascript中从数组创建树(父子)对象

Kes*_*007 3 javascript arrays nested typescript

我有一个像

[
  "parent1|child1|subChild1",
  "parent1|child1|subChild2",
  "parent|child2|subChild1",
  "parent1|child2|subChild2",
  "parent2|child1|subChild1",
  "parent2|child1|subChild2",
  "parent2|child2|subChild1",
.
.
.    
]
Run Code Online (Sandbox Code Playgroud)

其中我之前的第一个字符串|是父级,第二个字符串是 | 是孩子和第二后第三个字符串|是subchild

我怎样才能把这个数组转换成一个对象

[
 {
  "id": "parent1",
  "children":[
   {
    "id": "child1",
    "children":[
     {
      "id": "subChild1"
     }
    ]
   }
  ]
 }
]
Run Code Online (Sandbox Code Playgroud)

父 -> 子 -> 子子对象

基于塞巴斯蒂安的回答,我在下面尝试使用打字稿

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);
}
Run Code Online (Sandbox Code Playgroud)

但这给了我:

无法读取未定义的属性“genTree””错误

更新:

根据塞巴斯蒂安的评论更改self.genTreethis.genTree.bind(this)并且它没有任何问题

adi*_*iga 5

您可以使用mapper将每个对象映射到其唯一路径的对象(您可以使用 each 映射对象id,但id在这里不是唯一的)。然后reduce是数组中的每个部分项。将root对象设置为initialValue。累加器将是当前项目的父对象。在每次迭代中返回当前对象。

const input = [
    "parent1|child1|subChild1",
    "parent1|child1|subChild2",
    "parent1|child2|subChild1",
    "parent1|child2|subChild2",
    "parent2|child1|subChild1",
    "parent2|child1|subChild2",
    "parent2|child2|subChild1"
  ],
  mapper = {},
  root = { children: [] }

for (const str of input) {
  let splits = str.split('|'),
      path = '';

  splits.reduce((parent, id, i) => {
    path += `${id}|`;

    if (!mapper[path]) {
      const o = { id };
      mapper[path] = o; // set the new object with unique path
      parent.children = parent.children || [];
      parent.children.push(o)
    }
    
    return mapper[path];
  }, root)
}

console.log(root.children)
Run Code Online (Sandbox Code Playgroud)