Recursively flat an object JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a function that does the following transformation −

If the input object is −

const input = {
   a: 0,
   b: {x: {y: 1, z: 2}},
   c: 3
};

Then the output of the function should be −

const output = {
   a: 0,
   'b.x.y': 1,
   'b.x.z': 2,
   c: 3
}

We basically have to write a function that flattens a nested object. Will do this via recursion and the code for doing this will be −

Example

const obj = {
   a: 1,
   b: {x: {y: 1, z: 2}},
   c: 3
};
const obj1 = {
   a: 0,
   b: 0,
   c: 0
};
const object = { a: 0, b: { x: { y: 1, z: 2 } }, c: 3 };
const stringifyKeys = (obj, str = '', fresh = {}) => {
   const keys = Object.keys(obj);
   for(let i = 0; i < keys.length; i++){
      if(typeof obj[keys[i]] === "object" && !Array.isArray(obj[keys[i]])
      && obj[keys[i]]){
         stringifyKeys(obj[keys[i]], str+`${keys[i]}.`, fresh);
      }else{
         fresh[str+keys[i]] = obj[keys[i]];
      };
   }
   return fresh;
};
console.log(stringifyKeys(obj));
console.log(stringifyKeys(object));
console.log(stringifyKeys(obj1));

Output

The output in the console will be −

{ a: 1, 'b.x.y': 1, 'b.x.z': 2, c: 3 }
{ a: 0, 'b.x.y': 1, 'b.x.z': 2, c: 3 }
{ a: 0, b: 0, c: 0 }
raja
Published on 26-Aug-2020 09:37:43
Advertisements