1

I have a nested object:

{
  id: 240,
  name: 'FY1 2022',
  children: [
    {
      id: 241,
      name: 'Q1 2022',
      children: [
        {
          id: 242,
          name: 'Jan 2022',
        },
        {
          id: 243,
          name: 'Feb 2022',
        },
        {
          id: 244,
          name: 'Mar 2022',
        },
      ],
    },
  ],
};

and I need to get all the id values into an array from that objects that does not have the property children.

Is there a way to do this?

Thanks in advance!

2 Answers 2

3

You can try this:

type MyObject = {
   id: number, 
   name: string,
   children?: MyObject[]
}
function getIds(obj: MyObject): number[] {

   if (!obj.children) {
      return [obj.id];
   } 

   return obj.children.reduce((ids:number[],o: MyObject)=> {
     ids.push(...getIds(o))
     return ids
   },[]);
}
Sign up to request clarification or add additional context in comments.

Comments

3

try this (using recursion)

const test = {
  id: 240,
  name: 'FY1 2022',
  children: [
    {
      id: 241,
      name: 'Q1 2022',
      children: [
        {
          id: 242,
          name: 'Jan 2022',
        },
        {
          id: 243,
          name: 'Feb 2022',
        },
        {
          id: 244,
          name: 'Mar 2022',
        },
      ],
    },
  ],
};

function addToArray(array, obj) {
  if (obj.children) {
    obj.children.forEach(child => addToArray(array, child))
  } else {
    array.push(obj.id)
  }

  return array
}

const array = []

console.log(addToArray(array, test))

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.