Home > Enterprise >  How to get array of parents ids in nested Javascript object?
How to get array of parents ids in nested Javascript object?

Time:11-20

How to get an array of parent ids in a nested Javascript object ? Source object:

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 should get id and obj, for instance, I have input id = '08', the result array should be in this order ['01', '06', '08']

or id = '05', result ['01', '02', '04', '05']

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

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

CodePudding user response:

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'));

  • Related