Skip to content

Instantly share code, notes, and snippets.

@gavboulton
Last active July 26, 2017 19:02
Show Gist options
  • Save gavboulton/ad429910de298782bcc40769239fcb6a to your computer and use it in GitHub Desktop.
Save gavboulton/ad429910de298782bcc40769239fcb6a to your computer and use it in GitHub Desktop.
Flatten object keys
const flattenObject = obj => {
if (typeof obj !== 'object') {
return obj;
}
function flattenKeys(value, key, storedKey) {
const newKey = storedKey ? `${storedKey}.${key}` : key;
if (typeof value === 'object') {
const firstKey = Object.keys(value)[0];
return flattenKeys(value[firstKey], firstKey, newKey);
}
return { [newKey]: value };
}
return Object.keys(obj).reduce((memo, key) => {
return { ...memo, ...flattenKeys(obj[key], key) };
}, {});
};
describe('flattenObject', () => {
it('returns value if not an object', () => {
expect(flattenObject('string')).toEqual('string');
});
it('combines keys of nested objects', () => {
const res = flattenObject({
a: {
b: {
c: 1
}
},
d: 2
});
expect(res).toEqual({ 'a.b.c': 1, d: 2 });
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment