树状结构查找爹们

我有原始数据如下

const nodes = {
  id: "abc",
  name: "爷爷",
  children: [
    {
      id: "def",
      name: "爹",
      children: [{ id: "jkl", name: "我" }],
    },
  ],
};

如上数据 拿到某一层的item,但是并不会知道它的父级 父级的父级 父级的父级的父级是谁?
这该怎么办,简单 我处理完这个数据,加一个标识不就行了。

// 处理一边数据 加一个字段 用来获取ppppids
const hadelData = (nodes) => {
  const handel = (node, pnode) => {
    // param.fullId = param.id+pid;
    if (pnode) {
      // 当前的fullId=上级的fullId+自己的id
      node.fullId = pnode.fullId + "_" + node.id;
    } else {
      // 最顶层的fullId就等于自己的id
      node.fullId = node.id;
    }

    // 遍历 给所有元素加上这个fullId标识
    if (node.children) {
      node.children.forEach((element) => {
        handel(element, node);
      });
    }
  };
  const nodesCopy = {...nodes}; // 整一个副本 别把原始数据搞乱了
  handel(nodesCopy);
  return nodesCopy;
};

使用下试试,之后打印如下

const res = hadelData(nodes);
console.log(nodes, res);
{
    "id": "abc",
    "name": "爷爷",
    "fullId": "abc"
    "children": [
        {
            "id": "def",
            "name": "爹",
            "fullId": "abc_def"
            "children": [
                {
                    "id": "jkl",
                    "name": "我",
                    "fullId": "abc_def_jkl"
                }
            ],
        }
    ]
}

有了fullId这个字段 就好办多了

posted @   丁少华  阅读(63)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示