Skip to content

Instantly share code, notes, and snippets.

@a-tarasyuk
Last active August 3, 2016 11:17
Show Gist options
  • Save a-tarasyuk/904e059de5e9938ac7a48b0f6c5abb67 to your computer and use it in GitHub Desktop.
Save a-tarasyuk/904e059de5e9938ac7a48b0f6c5abb67 to your computer and use it in GitHub Desktop.
function isObject(value) {
return typeof value === 'object' && value !== null;
}
function flatten(data, result = {}, prefix = '') {
return Object
.keys(data)
.reduce(function (result, key) {
const path = prefix ? `${ prefix }.${ key }` : key;
if (isObject(data[key])) {
return flatten(data[key], result, path);
}
result[path] = data[key];
return result;
}, result);
}
// {x:1, y:1, z:{a:1,b:2}} flattens to {x:1, y:1, z.a:1, z.b: 2}
var data = {
x: 1,
y: 1,
z: {
a: 1,
b: 2,
z: {
x: 100,
a: {
a: 2
}
}
}
};
console.log(
flatten(data)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment