Search code examples
javascriptarraysreactjstypescriptnested-object

Extract sub-object from nested object typescript


Is there a way to extract a sub-object from a nested object?

For example I have the following object:

[
  {
    id: 370,
    name: 'FY 2022',
    children: [
      {
        id: 371,
        name: 'Q1 2022',
        children: [
          {
            id: 409,
            name: 'Jan 2022',
          },
          {
            id: 410,
            name: 'Feb 2022',
          },
          {
            id: 411,
            name: 'Mar 2022',
          },
        ],
      },
    ],
  },
];

if I send in a function as a parameter the id to return me the object corresponding with that id.

For example if I give as parameter id = 371 to return me:

[
  {
    id: 371,
    name: 'Q1 2022',
    children: [
      {
        id: 409,
        name: 'Jan 2022',
      },
      {
        id: 410,
        name: 'Feb 2022',
      },
      {
        id: 411,
        name: 'Mar 2022',
      },
    ],
  },
];

or if I give the id = 410 to return:

 [
  {
    id: 410,
    name: 'Feb 2022',
  },
];

Thanks in advance!


Solution

  • You can do something like this

    const findById = (data, id) => {
     if(data.length === 0){
       return []
     }
     const el = data.find(d => d.id === id)
     if(el){
       return [el]
     }
     return findById(data.flatMap(d => d.children || []), id)
    }
    
    
    const data = [
      {
        id: 370,
        name: 'FY 2022',
        children: [
          {
            id: 371,
            name: 'Q1 2022',
            children: [
              {
                id: 409,
                name: 'Jan 2022',
              },
              {
                id: 410,
                name: 'Feb 2022',
              },
              {
                id: 411,
                name: 'Mar 2022',
              },
            ],
          },
        ],
      },
    ];
    
    console.log(findById(data, 370))
    console.log(findById(data, 409))
    console.log(findById(data, 4090))