Search code examples
javascriptnestedjavascript-objects

How to get nested Javascript object when depth is unknown?


Suppose I have these arrays:

const array1 = [
   {
      data: {
         site: {
            tag: {
               name: "Bikes", 
               posts: { ... }
            }
         }
      },
      errors: {}
   },
   { ... }   
]

const array2 = [
   {
      data: {
         category: {
            name: "Cars", 
            posts: { ... }
         }
      },
      errors: {}
   },
   { ... }   
]

const array3 = [
   {
      data: {
         posts: { ... }
      },
      errors: {}
   }, 
   { ... }  
]

What function can I use on array 1 and 2 so that I am always left with an array shaped like array 3? How can I always extract posts from data without knowing at what position it is in the nested object?

I've tried a few things with find or filter or recursive functions but I'm just no good at this, sorry. Hope somebody can help!


Solution

  • After digging a bit deeper, I've got it working with this:

    const result = []
    
    const getPosts = obj => {
    
       if( obj?.posts ) {
          return obj.posts
       } 
            
       for( const key of Object.values( obj ) ) {
          return getPosts(key)
       }
       
    }
         
    array1.forEach( item => { // Also works with array2
       result.push({ 
          data: {
             posts: getPosts( item.data )
          },
          errors: item.errors 
       })
    })
    
    console.log( result ) // result will look like array3