Last active
July 26, 2017 19:02
-
-
Save gavboulton/ad429910de298782bcc40769239fcb6a to your computer and use it in GitHub Desktop.
Flatten object keys
This file contains 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 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