Skip to content

Instantly share code, notes, and snippets.

@abhinavnigam2207
Created May 18, 2018 23:02
Show Gist options
  • Save abhinavnigam2207/858a019e34d4215955b5111eb74315be to your computer and use it in GitHub Desktop.
Save abhinavnigam2207/858a019e34d4215955b5111eb74315be to your computer and use it in GitHub Desktop.
Flatten an object recursively (Asked in Wingify Interview)
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;
};
@abhinavnigam2207
Copy link
Author

Write an implementation of a function called flatten that flattens a nested object. The method takes an object and returns a new flattened object.

Base structure:

function flatten(obj) {
 // should return a new flattened object.
}

For example:
For the given input object,

var inputObj = {
        'name': 'jane',
        'last_name': 'doe',
        'profession': 'engineer',
        'characteristics': {
                'intelligent': true,
                'punctual': false,
                'experience': {
                        '2012': 'college passout',
                        '2014': 'mba passout',
                        '2016': 'employed'
                }
        }
};

flatten(inputObj);

Output:

{
        'name': 'jane',
        'last_name': 'doe',
        'profession': 'engineer',
        'characteristics.intelligent': true,
        'characteristics.punctual': false,
        'characteristics.experience.2012': 'college passout',
        'characteristics.experience.2014': 'mba passout',
        'characteristics.experience.2016': 'employed'
}

Note: The method should NOT modify the original object. It should return a new object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment