Flatting An object and Array Using Recursion and other Methods

Ashish mauryaAshish maurya
3 min read

Hello Guys,

How are you? I decided to write small snippets of code and hacks I find while developing things that might help you guys too.

So Today I Will be showing a recursive way to flatten an array and object . This gonna be a short tutorial for you guys.

Accesing a nested object using Recursion.

We will be flattening the below Object using our custom-built recursive Function.

sample object


{
  "isbn": "123-456-222",
  "author":
  {
    "lastname": "Doe",
    "firstname": "Jane",
    "address": {
      "street":"3856 Pooz Street",
      "city":"South River",
      "state":"New Jersey",
      "counrty":"United State", 
    }
  },
  "title": "The Ultimate Database Study Guide",
  "category": ["Non-Fiction", "Technology"]
}

The source Code for the Recursive function

const flat_an_object =(object)=>{

  let result = {}

  const recursiveFunction = (obj)=>{
    for (const key in obj){
      if(typeof obj[key] === "object" && 
         Array.isArray(obj[key]) ===false){
        recursiveFunction(obj[key])
      }
      else{
        result ={...result, [key] : obj[key] }
      }
    }
  }
  recursiveFunction(object);
  return result; 
}

you might ask why I have used the Array.isArray() method in the condition, let's see what is the reason if we remove this method from the Array then what kind of nested object we will get and how that flatten the object will look like.

This is the result of the flattened Object.


{
  '0': 'Non-Fiction',
  '1': 'Technology',
  isbn: '123-456-222',
  lastname: 'Doe',
  firstname: 'Jane',
  street: '3856 Pooz Street',
  city: 'South River',
  state: 'New Jersey',
  counrty: 'United State',
  title: 'The Ultimate Database Study Guide'
}

Here you can see that the object contains an array and it's also getting flattened. I recently posted a tweet about this too and you can see it here to know more about this behavior in Javascript.

after using that Array.isArray() method we will be getting the flattened Object. Now the object is not a nested object anymore.

results:

{
  isbn: '123-456-222',
  lastname: 'Doe',
  firstname: 'Jane',
  street: '3856 Pooz Street',
  city: 'South River',
  state: 'New Jersey',
  counrty: 'United State',
  title: 'The Ultimate Database Study Guide',
  category: [ 'Non-Fiction', 'Technology' ]
}

Flattening An Array or Accessing a nested Array

The same method can be applied to flatten an Array to the thing we change is instead of saying typeof Object === "object" we will use Array.isArray(key).

Let's see the code.

sample array



const sampleArray = [1, 2, 3, [4, 5, 6, [7, 8]]]

to flatten this array we will just use our previous function and recursively traverse them.


const flatAnArray = (array) => {

  let result = []

  // Todo : Define a level 

  const recursiveFunction = (arr) => {
    for (const key in arr) {
      if (Array.isArray(arr[key])) {
        recursiveFunction(arr[key])
      }
      else {
        result.push(arr[key])
      }
    }
  }
  recursiveFunction(array);
  return result;
}

the output of our code is as follows, we flattened our nested Array.

[1, 2, 3, 4,5, 6, 7, 8]

Other ways of flattening an Array.

There are several ways to flatten a nested Array in javascript and some inbuild methods are Array.flat() method with a depth infinity.

const arr = [1, 2, 3, [4, 5, 6, [7, 8]]]

console.log(arr.flat(infinity))

output :

[1, 2, 3, 4,5, 6, 7, 8]

Flattening with a depth of 1

1 . using reduce()

let flatArray = arr.reduce((acc, curVal) => {
    return acc.concat(curVal)
}, []);

console.log(flatArray)
  1. using concat() with apply()
let flatArray1  = [].concat.apply([], arr);

outputs:


[ 1, 2, 3, 4, 5, 6, [ 7, 8 ] ]

TL;DR

  1. Use recursion to flat a nested object by looping over each property and checking if the typeof the property is of type object, then recursively loop over that object and keep adding the result to the result object.

  2. Use Array.flat() method in case of flattening a nested Array.

50
Subscribe to my newsletter

Read articles from Ashish maurya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ashish maurya
Ashish maurya

I am a developer from India with a good eye for frontend logic and design. I am also well acquainted with the backend and business logic so that's add to my ability to create a good frontend while making it easily integratable with backend.