下面是一个示例代码实现:

const addIndexToTree = (tree, index = '') => {
  if (Array.isArray(tree)) { // 处理数组
    return tree.map((item, i) => {
      const currentIndex = `${index}-${i + 1}`;
      return addIndexToTree(item, currentIndex);
    });
  } else if (typeof tree === 'object' && tree !== null) { // 处理对象
    return Object.keys(tree).reduce((acc, key) => {
      const currentIndex = index ? `${index}-${key}` : key;
      acc[key] = addIndexToTree(tree[key], currentIndex);
      return acc;
    }, {});
  } else { // 处理其他类型
    return tree;
  }
};

// 示例
const data = {
  a: {
    b: {
      c: [
        { d: 1 },
        { d: 2 },
      ],
    },
    e: 3,
  },
  f: [
    { g: 4 },
    { h: {
      i: 5,
      j: [
        { k: 6 },
        { k: 7 },
      ],
    }},
  ],
};

console.log(addIndexToTree(data)); 
// 输出:
// {
//   "a": {
//     "b": {
//       "c": [
//         { "d": "1", "index": "1-1" },
//         { "d": "2", "index": "1-2" }
//       ],
//       "index": "1"
//     },
//     "e": 3,
//     "index": "2"
//   },
//   "f": [
//     {
//       "g": "4",
//       "index": "1"
//     },
//     {
//       "h": {
//         "i": "5",
//         "j": [
//           { "k": "6", "index": "1-1" },
//           { "k": "7", "index": "1-2" }
//         ],
//         "index": "2"
//       },
//       "index": "2"
//     }
//   ]
// }

该函数接受两个参数,第一个参数是要处理的树形结构数据,第二个参数是当前处理的层级下标。在处理数组时,会遍历数组中的每个元素,并在当前下标的基础上增加 1-1、1-2、1-3 等下标,最终返回一个处理后的数组。在处理对象时,会遍历对象的每个键值对,并在当前下标的基础上增加该键的下标,然后递归处理该键对应的值,最终返回一个处理后的对象。在处理其他类型时,直接返回该值即可。最后,处理完整个树形结构数据后,会在每个对象中添加一个 index 属性,表示该对象的层级下标

es6 针对对象树形结构数据 使用递归 增加对应层级下标 如每个对象 增加 11-11-21-1-11-1-2

原文地址: https://www.cveoy.top/t/topic/hlir 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录