Skip to content

Instantly share code, notes, and snippets.

@petervmeijgaard
Last active June 14, 2021 08:03
Show Gist options
  • Save petervmeijgaard/58856005e6fbdcc098ff669851becc5d to your computer and use it in GitHub Desktop.
Save petervmeijgaard/58856005e6fbdcc098ff669851becc5d to your computer and use it in GitHub Desktop.
Recursive Object to Dot Notation Helper
const isObject = value => typeof value === 'object' && value !== null && !Array.isArray(value);
const getDottedKey = (current, parent = null) => (parent ? `${parent}.${current}` : current);
const objectToDotNotation = (value, key = null, carry = {}) => {
if (!isObject(value) && !key) {
return value;
}
if (!isObject(value)) {
return { ...carry, [key]: value };
}
return Object.entries(value).reduce((childCarry, [childKey, childValue]) => (
objectToDotNotation(childValue, getDottedKey(childKey, key), childCarry)
), carry);
};
// => { foo: 'bar' }
objectToDotNotation({
foo: 'bar'
});
// => { foo: 'bar', 'bar.baz' => 'foo' }
objectToDotNotation({
foo: 'bar',
bar: {
baz: 'foo'
}
});
// => { 'foo.bar.baz.hello': 'world!' }
objectToDotNotation({
foo: { bar: { baz: { hello: 'world!' } } }
});
objectToDotNotation(''); // => ''
objectToDotNotation(null); // => null
objectToDotNotation(['one', 'two', 'three']) // => ['one', 'two', 'three']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment