js中數(shù)組處理以及數(shù)據(jù)對象的處理

一、顯示菜單:使用樹形結(jié)構(gòu)分組,把數(shù)據(jù)a變成數(shù)據(jù)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 = [];
  
  // 首先創(chuàng)建所有項的映射
  items.forEach(item => {
    itemMap[item.id] = { ...item, children: [] };
  });
  
  // 構(gòu)建樹結(jié)構(gòu)
  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);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容