Last active
June 14, 2021 08:03
-
-
Save petervmeijgaard/58856005e6fbdcc098ff669851becc5d to your computer and use it in GitHub Desktop.
Recursive Object to Dot Notation Helper
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 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); | |
}; |
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
// => { 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