Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Recursively flat an object JavaScript
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 }Advertisements