Created
May 18, 2018 23:02
-
-
Save abhinavnigam2207/858a019e34d4215955b5111eb74315be to your computer and use it in GitHub Desktop.
Flatten an object recursively (Asked in Wingify Interview)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const flatten = function(inputObj) { | |
| var respObj = {}; | |
| for (let i in inputObj) { | |
| if (!inputObj.hasOwnProperty(i)) continue; | |
| if ((typeof inputObj[i]) == 'object') { | |
| let flatObject = flatten(inputObj[i]); | |
| for (let x in flatObject) { | |
| if (!flatObject.hasOwnProperty(x)) continue; | |
| respObj[i + '.' + x] = flatObject[x]; | |
| } | |
| } else { | |
| respObj[i] = inputObj[i]; | |
| } | |
| } | |
| return respObj; | |
| }; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Write an implementation of a function called
flattenthat flattens a nested object. The method takes an object and returns a new flattened object.Base structure:
For example:
For the given input object,
flatten(inputObj);
Output:
Note: The method should NOT modify the original object. It should return a new object.