Flatten a nested object using javascript

Question

Flatten the given nested object. The nesting can be upto n levels.

For the below input

const input = {

  a: 10,

  b: 'foo',

  c: {

    d: 'bar',

    e: false,

    f: {

      g: 'random',

    },

  },

  d: 'test',

};


the output should look like this:

// Output = {a: 10, b: 'foo', c.d: 'bar', c.e: false, c.f.g: 'random', d: test}


Solution

Lets write a function to flatten the above object.

// Lets take a temporary object to save the flatten values

let output = {};

function formatObject(object, prefix) {

    // iterate over the attributes of the current object

  Object.keys(object).forEach((key) => {

    let value = object[key];

    if (typeof value !== 'object') {

      console.log('if 1: ', value, prefix);

      if (prefix) {

        // ex: c.f.g: 'random'

        output[`${prefix}.${key}`] = value;

      } else {

        // ex: a: 10

        output[key] = value;

      }

    } else {

      console.log('else 1: ', value, prefix);

      // In case prefix is empty just send the key

      let tmpPrefix = prefix ? `${prefix}.${key}` : key;

      // call this recursively to flatten the nested objects.

      formatObject(value, tmpPrefix);

    }

  });

  return output;

}


console.log('Flatten Object: ', formatObject(input));


Checkout my other such inteview questions my other blogs here: https://abhijitpadhy.blogspot.com/

Comments

Popular posts from this blog

Abhijit Padhy

Find the longest substring in a given string.

Find the robot matching the given query having [top, right, bottom, left] index of the nearest walls in a 2D array.