Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript get all values of a property from a nested object

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance!

>Solution :

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
   },[]);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading