Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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 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
