js怎么获取数组对象中指定id的父对象

罗小懒丶
  • 51
let data = [
       {
        title: "江苏",
        key: "34fggg",
        children: [
          {
            title: "苏州",
            key: "sdf34",
            children: [
              { title: "吴中", key: "rt3we" },
              { title: "姑苏", key: "34rff" },
              { title: "园区", key: "34gdf" }
            ]
          },
          {
            title: "南京",
            key: "8kgkk",
            children: [
              { title: "鼓楼", key: "gdthj" },
            ]
          },
          {
            title: "无锡",
            key: "54y5y"
          }
        ]
      },
      {
        title: "浙江",
        key: "94kr"
      }
    ]

比如我知道‘吴中’的key是1-1-1
怎么获取‘苏州’的key

回复
阅读 735
3 个回答

请看代码,利用递归和es6 some方法去遍历,如有帮助,望采纳

let getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
            if (node.children.some(item => item.key === key)) {
                parentKey = node.key;
            } else if (getParentKey(key, node.children)) {
                parentKey = getParentKey(key, node.children);
            }
        }
    }
    return parentKey;
};

image.png

既然是要找到父级,那就将父级当成参数传递一下好了,然后挨层遍历,下面有个简单的实现可以参考一下,具体的返回值,还有是不是区分找到的是第一层没有父级,还是所有都没有找到,可以在返回值上做些处理。

const findParentKeyByChildKey = (data, key) => {
    return (function loop(data, parent, key) {
        for (const child of data) {
            if (child.key === key) {
                return parent && parent.key;
            }
            let parentKey;
            if (child.children && (parentKey = loop(child.children, child, key)) !== null) {
                return parentKey;
            }
        }
        return null;
    })(data, null, key);
};

一个比较清晰及避免重复计算的思路和实现过程是:

  1. 先构建反向字典表,子ID => 父ID
  2. 然后根据字典表中子ID获取父ID
// 用类的方式避免重复计算
class ParentDict {
  dict = new Map()  
  constructor(data) {
    const process = (children, key) => {
      for (const child of children) {
        this.dict.set(child.key, key)
        if (Array.isArray(child.children)) {
          process(child.children, child.key)
        }
      }
    }
    process(data, null)
  }
  getPid(cid) {
    return this.dict.get(cid)
  }
}

const dict = new ParentDict(data)

dict.getPid('1-1-2')  // 输出 1-1
dict.getPid('1-1')    // 输出 1
宣传栏