如何获取嵌套Javascript对象中的父id数组?

wz3gfoph  于 2022-11-20  发布在  Java
关注(0)|答案(1)|浏览(149)

如何在嵌套的Javascript对象中获取父id数组?源对象:

const obj = {
  id: '01',
  children: [
    {
      id: '02',
      children: [
        {
          id: '03',
          children: [],
        },
        {
          id: '04',
          children: [
            {
              id: '05',
              children: [],
            }
          ],
        }
      ],
    },
    {
      id: '06',
      children: [
        {
          id: '07',
          children: [],
        },
        {
          id: '08',
          children: [
            {
              id: '09',
              children: [],
            }
          ],
        }
      ],
    },
  ]
}

Func应该得到id和obj,例如,我有输入id = '08',结果数组应该是这个顺序['01','06','08']
或标识= '05',结果['01',' 02 ',' 04 ',' 05 ']

const getParentsArr = (obj, id) => {
  const arr = []
  arr.push(obj.id)

  function recursiveFind(children) {
    ...
  }
  return recursiveFind(obj.children);
}
ckx4rj1h

ckx4rj1h1#

const obj = {"id":"01","children":[{"id":"02","children":[{"id":"03","children":[]},{"id":"04","children":[{"id":"05","children":[]}]}]},{"id":"06","children":[{"id":"07","children":[]},{"id":"08","children":[{"id":"09","children":[]}]}]}]};

const f = (obj, id) => [obj.id,
  ...obj.children.map(c=>f(c,id)).find(i=>i.includes(id))??[]];

console.log(f(obj, '05'));

相关问题