递归查找——通过某个属性从树结构中获取对象

假定现有树结构:

const personArr = [
  {
    id: "001",
    name: "maimang",
    children: [
      {
        id: "002",
        name: "Tom",
        headImg: "https://avatars1.githubusercontent.com/u/24405319?s=460&v=4"
      },
      {
        id: "003",
        name: "Jerry",
        headImg: "https://avatars1.githubusercontent.com/u/24405319?s=460&v=4"
      },
      {
        id: "006",
        name: "业务部",
        children: [
          {
            id: "007",
            name: "小明",
            headImg:
              "https://avatars1.githubusercontent.com/u/24405319?s=460&v=4"
          },
          {
            id: "008",
            name: "小话",
            headImg:
              "https://avatars1.githubusercontent.com/u/24405319?s=460&v=4"
          },
          {
            id: "009",
            name: "小王",
            headImg:
              "https://avatars1.githubusercontent.com/u/24405319?s=460&v=4"
          }
        ]
      },
      {
        id: "010",
        name: "test",
        headImg: "https://avatars1.githubusercontent.com/u/24405319?s=460&v=4"
      }
    ]
  }
];

要通过id找到对应的对象,并返回对象里面的children

封装函数如下:

function getCurrentPart(id, items) {
  let result;
  for (var i in items) {
    let item = items[i];
    if (item.id == id) {
      result = item.children;
      break;
    } else if (item.children) {
      result = getCurrentPart(id, item.children);
    }
  }
  return result;
}

调用:

var result=getCurrentPart('006',personArr);
console.log(result);

结果:



猜你喜欢

转载自blog.csdn.net/qq_36111804/article/details/80941110