js中数组处理以及数据对象的处理

一、显示菜单:使用树形结构分组,把数据a变成数据b

let  a= {
  "data": [
  { id: 1, title: "menu1", parentId: 0 },
  { id: 2, title: "menu2", parentId: 0 },
  { id: 3, title: "menu1_1", parentId: 1 },
  { id: 4, title: "menu1_2", parentId: 1 },
  { id: 5, title: "menu2_1", parentId: 2 },
  ],
  "message": "操作成功",
  "code": 200
}

let b=[
    {
        "id": 1,
        "title": "menu1",
        "parentId": 0,
        "children": [
            {
                "id": 3,
                "title": "menu1_1",
                "parentId": 1,
                "children": []
            },
            {
                "id": 4,
                "title": "menu1_2",
                "parentId": 1,
                "children": []
            }
        ]
    },
    {
        "id": 2,
        "title": "menu2",
        "parentId": 0,
        "children": [
            {
                "id": 5,
                "title": "menu2_1",
                "parentId": 2,
                "children": []
            }
        ]
    }
]
1、方法一:使用递归
function buildTree(items, parentId = 0) {
  return items
    .filter(item => item.parentId === parentId)
    .map(item => ({
      ...item,
      children: buildTree(items, item.id)
    }));
}

// 使用示例
const flatData = [
  { id: 1, title: "menu1", parentId: 0 },
  { id: 2, title: "menu2", parentId: 0 },
  { id: 3, title: "menu1_1", parentId: 1 },
  { id: 4, title: "menu1_2", parentId: 1 },
  { id: 5, title: "menu2_1", parentId: 2 },
];

const treeData = buildTree(flatData);
console.log(treeData);
2、方法二:使用 reduce 和对象引用
function buildTreeWithReduce(items) {
  const itemMap = {};
  const tree = [];
  
  // 首先创建所有项的映射
  items.forEach(item => {
    itemMap[item.id] = { ...item, children: [] };
  });
  
  // 构建树结构
  items.forEach(item => {
    if (item.parentId === 0) {
      tree.push(itemMap[item.id]);
    } else {
      if (itemMap[item.parentId]) {
        itemMap[item.parentId].children.push(itemMap[item.id]);
      }
    }
  });
  
  return tree;
}

const treeData = buildTreeWithReduce(flatData);
console.log(treeData);
3、方法三:使用 Map 对象(ES6)
function buildTreeWithMap(items) {
  const map = new Map();
  const tree = [];
  
  items.forEach(item => {
    map.set(item.id, { ...item, children: [] });
  });
  
  for (const item of map.values()) {
    if (item.parentId === 0) {
      tree.push(item);
    } else {
      const parent = map.get(item.parentId);
      if (parent) {
        parent.children.push(item);
      }
    }
  }
  
  return tree;
}

const treeData = buildTreeWithMap(flatData);
console.log(treeData);
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容