首页 > 其他分享 >根据key 获取父级 和本身 key值

根据key 获取父级 和本身 key值

时间:2024-04-29 18:34:29浏览次数:18  
标签:getopenkey name 父级 age 获取 result key children

var data = [
  {
    key: 1,
    name: "1",
    pd:0,
    age: 60,
    address: "1",
    children: [
      {
        key: 11,
        name: "1-1",
        age: 42,
      },
      {
        key: 12,
        name: "1-2",
        age: 30,
        children: [
          {
            key: 121,
            name: "1-2-1",
            age: 16,
          },
        ],
      },
      {
        key: 13,
        name: "1-3",
        age: 72,
        children: [
          {
            key: 131,
            name: "1-3-1",
            age: 42,
            children: [
              {
                key: 1311,
                name: "1-3-1-1",
                age: 25,
              },
              {
                key: 1312,
                name: "1-3-1-2",
                age: 18,
              },
            ],
          },
        ],
      }
    ],
  },
  {
    key: 2,
    name: "2",
    age: 32,
    address: "2",
    pd:0
  },
]
const getopenkey = (arr, item, parentKeys = []) => {
  let result = [];
  arr.forEach((v) => {
    const currentKeys = [...parentKeys, v.key];
    if (String(v.key).includes(item)) {
      result.push(...currentKeys);
    }
    if (v.children && v.children.length) {
      result = result.concat(getopenkey(v.children, item, currentKeys));
    }
  });
  return result;
};

let element = 121;
let result = getopenkey(data, element);
console.log(JSON.stringify(result)); // 应该返回 [1, 12, 121]

 

标签:getopenkey,name,父级,age,获取,result,key,children
From: https://www.cnblogs.com/zxh-bug/p/18166469

相关文章