js 如何获取value值的路径?

比如这样一个数据结构
`

let data={
    id: "first",  
    type: "list",
    children:[
      {
       id:"second0",
       type:"list",
       children:[
          {
            id:"third0",
            type:"list",
          },
          {
            id:"third1",
            type:"list",
          },
       ]
      },
      {
       id:"second1",
       type:"list"
      },
    ]
}

`

如何根据third1,获取到的结果为:first/second0/third1 ?求大神指点

阅读 2.6k
2 个回答
const findPath = (function() {
  return function findPathInstance(obj, id, path = []) {
    if (obj.id === id) {
      findPathInstance._path = [...path, id].join("/");
    } else {
      if (obj.children) {
        obj.children.forEach(child => findPath(child, id, [...path, obj.id]));
      }
    }
  };
})();

findPath(data, "third1");
console.log(findPath._path);

你多去学学递归或者迭代的思想,这类问题都是这么处理的。我的答案仅供参考,谢谢

略微改动了下数据结构 给最外层也设置了数组。仅供参考哈。

let data = [
  {
    id: "first",
    type: "list",
    children: [
      {
        id: "second0",
        type: "list",
        children: [
          {
            id: "third0",
            type: "list"
          },
          {
            id: "third1",
            type: "list"
          }
        ]
      },
      {
        id: "second1",
        type: "list"
      }
    ]
  },
  {
    id: "first1",
    type: "list",
    children: [
      {
        id: "second2",
        type: "list"
      }
    ]
  }
];

function findP(data, p, path = []) {
  if (
    data.some(item => {
      if (item.id === p) {
        path.push(item.id);
        return true;
      } else if (item.children) {
        path.push(item.id);
        if (findP(item.children, p, path)) {
          return true;
        } else {
          path = [];
          return false;
        }
      } else {
        return false;
      }
    })
  ) {
    return path;
  } else {
    return null;
  }
}

let res = findP(data, "third1");

console.log(res);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题