javascript将树形菜单转换为数组的结构

// 原始树形菜单结构
const treeMenu = [
  {
    id: 1,
    name: "Home",
    children: [
      {
        id: 2,
        name: "About",
        children: []
      },
      {
        id: 3,
        name: "Services",
        children: [
          {
            id: 4,
            name: "Web Development",
            children: []
          },
          {
            id: 5,
            name: "Design",
            children: []
          }
        ]
      }
    ]
  }
];

// 转换为数组结构的方法
function convertTreeToArray(tree) {
  const result = [];
  tree.forEach(node => {
    const newNode = { id: node.id, name: node.name };
    if (node.children.length > 0) {
      newNode.children = convertTreeToArray(node.children);
    }
    result.push(newNode);
  });
  return result;
}

// 转换后的数组结构
const arrayStructure = convertTreeToArray(treeMenu);
console.log(arrayStructure);

你可能感兴趣的:(javascript,javascript,前端,开发语言)