Flatten the Object – JavaScript

Good day, Hope you are doing effectively & fixing fascinating issues utilizing your programming expertise.πŸ”₯

On this weblog, we are going to attempt to resolve one such fascinating downside associated to flattening the item which is requested in javascript interviews.

I’ve breakdown the entire tutorial into 4 sections –

  1. Enter
  2. Output
  3. Strategy (logic)
  4. Assemble (put every part collectively)

Let’s begin!πŸš€



Enter

That is our unflatten object containing knowledge of an consumer.

const consumer = {
  identify: 'John',
  handle: {
    private: {
      road: 'Victor Plains',
      metropolis: 'Wisokyburgh',
    },
    workplace: {
      metropolis: 'South Elvis',
      space: {
        landmark: 'Hoeger Mall',
      },
    },
  },
};
Enter fullscreen mode

Exit fullscreen mode



Output

We have to flat the item like this –

{
  user_name: "John",
  user_address_personal_street: "Victor Plains",
  user_address_personal_city: "Wisokyburgh",
  user_address_office_city: "South Elvis",
  user_address_office_area_landmark: "Hoeger Mall"
}
Enter fullscreen mode

Exit fullscreen mode



Strategy

When you carefully take a look at our enter object, you will see a sample of nested objects.

const OBJECT = {
  identify: 'John',
  OBJECT: {
    OBJECT: {
      road: 'Victor Plains',
      metropolis: 'Wisokyburgh',
    },
    OBJECT: {
      metropolis: 'South Elvis',
      OBJECT: {
        landmark: 'Hoeger Mall',
      },
    },
  },
};
Enter fullscreen mode

Exit fullscreen mode

So we have to iterate over the nested objects & flat them one after the other.
But when we wish to flat every object at a time, we have to breakdown the nested objects right into a single object recursively.

Recursively? πŸ€”

Sure, We are going to use recursion to resolve this downside.



What’s Recursion?

Recursion is a phenomenon used to resolve complicated issues by breaking them down into less complicated ones.



Recursive Perform

Once we apply this phenomenon in a perform, that perform will name itself time and again till we attain on the breaking situation.

*Let’s outline our recursive perform – *

const recursiveFunc = (obj, parentKey, flattenObj) => { 
  // we are going to write our logic right here.
};
Enter fullscreen mode

Exit fullscreen mode

  • obj: our enter object
  • parentKey: To maintain a observe of guardian object as a result of we have to append guardian keys whereas iterating over the enter obj – user_address_office_area_landmark: "Hoeger Mall"
  • flattenObj: an empty object to retailer flatten obj on every iteration.

Whereas looping by means of unflatten object, we are going to solely flat these key whose sort is object.

So, we’d like a perform which takes key as merchandise & return true if the bottom line is an object.

const isAnObject = (merchandise) => {
    return (
      merchandise !== null &&
      typeof merchandise === 'object' &&
      Object.prototype.toString.name(merchandise) === '[object Object]'
    );
  };
Enter fullscreen mode

Exit fullscreen mode

Now we have to loop by means of the enter object ( unflatten ) & retailer the flatten key-value pair inside flattenObj

for (let key in obj) { // 1
    let finalKey = `${parentKey}_${key}`; // 2
    if (isAnObject(obj[key])) { // 3
      recursiveFunc(obj[key], finalKey, flattenObj); // 4
    } else {
      flattenObj[finalKey] = obj[key]; // 5
    }
  }
Enter fullscreen mode

Exit fullscreen mode

Let’s perceive it line by line.

// 1 – let key in obj this line will give key of the key-value pair on every iteration. identify, handle, private & so on.

// 2 – we’re including the guardian key earlier than present key to make it seem like this on the finish – user_address_personal_street: "Victor Plains". Once we iterate over handle obj, the consumer would be the guardian. so we add the consumer earlier than handle – user_address & retailer it in finalKey.

// 3 – we’re checking if the present key’s an object or not utilizing isAnObject perform which we have already outlined.

// 4 – If the bottom line is an object, we are going to name recursiveFunc once more with the up to date worth of obj, parentKey & flattenObj.

// 5 – If the bottom line is not object, we are going to retailer the finalKey (user_address_personal_street) as key & key(“Victor Plains”) as worth inside flattenObj.

Let’s move our preliminary knowledge & console the output.

let flattenObj = {};
recursiveFunc(consumer, 'consumer', flattenObj);
console.log(flattenObj);
Enter fullscreen mode

Exit fullscreen mode

So once we invoke the recursiveFunc, it’s going to run the loop & iterate over consumer object.
Preliminary worth –

  1. obj: consumer
  2. parentKey: ‘consumer’
  3. flattenObj: {}



First Iteration

Now key is identify

  • finalKey = ‘user_name’
  • identify is just not an object
    Outcome
flattenObj = { user_name: "John" }
Enter fullscreen mode

Exit fullscreen mode



Second Iteration

Now key is handle

  • finalKey = ‘user_address’
  • handle is an object

Outcome
name recursiveFunc once more with new values –

  • obj: handle
  • parentKey: “user_address”
  • flattenObj: { user_name: "John" }



Third Iteration

Now key is private

  • finalKey = ‘user_address_personal’
  • private is an object

Outcome
name recursiveFunc once more with new values –

  • obj: private
  • parentKey: “user_address_personal”
  • flattenObj: { user_name: "John" }



Fourth Iteration

Now key is road

  • finalKey = ‘user_address_personal_street’
  • road is just not an object

Outcome

flattenObj = { 
  user_name: "John",
  user_address_personal_street: "Victor Plains"
}
Enter fullscreen mode

Exit fullscreen mode

…and iterations will go on till it attain the final key.
The ultimate output will probably be – πŸŽ‰

flattenObj = {
  user_name: "John",
  user_address_personal_street: "Victor Plains",
  user_address_personal_city: "Wisokyburgh",
  user_address_office_city: "South Elvis",
  user_address_office_area_landmark: "Hoeger Mall"
}
Enter fullscreen mode

Exit fullscreen mode



Assemble

Here is the entire code for flattening an object.

const consumer = {
  identify: 'John',
  handle: {
    private: {
      road: 'Victor Plains',
      metropolis: 'Wisokyburgh',
    },
    workplace: {
      metropolis: 'South Elvis',
      space: {
        landmark: 'Hoeger Mall',
      },
    },
  },
};

const recursiveFunc = (obj, parentKey, flattenObj) => { 
  const isAnObject = (merchandise) => { 
    return (
      merchandise !== null &&
      typeof merchandise === 'object' &&
      Object.prototype.toString.name(merchandise) === '[object Object]'
    );
  };

  for (let key in obj) { 
    let finalKey = `${parentKey}_${key}`; 
    if (isAnObject(obj[key])) {
      recursiveFunc(obj[key], finalKey, flattenObj); 
    } else {
      flattenObj[finalKey] = obj[key]; 
    }
  }
};

let flattenObj = {};
recursiveFunc(consumer, 'consumer', flattenObj);
console.log(flattenObj);

Enter fullscreen mode

Exit fullscreen mode



Conclusion

Hope after studying this weblog, you have understood –

  1. Methods to method an issue.
  2. Methods to flatten an object utilizing recursion.

When you discover this weblog as useful, do not forget to share it.
And incase you understand some other methods to flatten an object in javaScript, please share it within the feedback.

Thanks πŸ™‚
Join with me on – Twitter Instagram



Add a Comment

Your email address will not be published. Required fields are marked *