js 树形结构如何转为扁平化结构

丨VuDZ3
  • 5
新手上路,请多包涵

// 把树结构转为列表平行结构

  let tree = [
    {
      id: 1,
      name: "hei",
      children: [
        { id: 3, name: "bai" },
        { id: 4, name: "hong", children: [{ id: 6, name: "lv" }] }
      ]
    },
    { id: 2, name: "jack", children: [{ id: 5, name: "lan" }] }
  ];

  let list = [
    { id: 1, name: "hei" },
    { id: 3, name: "bai" },
    { id: 4, name: "hong" },
    { id: 6, name: "lv" },
    { id: 2, name: "jack" },
    { id: 5, name: "lan" },
  ];
回复
阅读 1.6k
3 个回答
var data = [
    {
        id: 1,
        name: "hei",
        children: [
            { id: 3, name: "bai" },
            { id: 4, name: "hong", children: [{ id: 6, name: "lv" }] }
        ]
    },
    { id: 2, name: "jack", children: [{ id: 5, name: "lan" }] }
];
var result = [];
function flatTree(data){
    data.forEach(item => {
        result.push({
            id: item.id,
            name: item.name
        })
        if(item.children?.length){
            result=flatTree(item.children);
        }
    });
    return result
}
flatTree(data)

image.png

function preOrder(list, result=[]) {
    list.forEach(node => {
        result.push({id: node.id, name: node.name})
        if(node.children) preOrder(node.children, result);
    })
    return result;
}
function preOrder(list) {
    return list.reduce((res,node) => {
        res.push({id: node.id, name: node.name})
        if(node.children) res = res.concat(preOrder(node.children));
        return res
    }, [])
}
let list = ((a,b=[],f=a=>(a.forEach(i=>(b.push({id:i.id,name:i.name}),i.children && f(i.children))),b))=>f(a))(tree);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏