2

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.