Last active
September 25, 2020 09:35
-
-
Save jniac/39eabea6b06a9be5be348c11447c249c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // https://gist.github.com/jniac/39eabea6b06a9be5be348c11447c249c | |
| /** | |
| * 'prune' will simplify any tree (target) by removing any 'autoKey' | |
| * found by its inner value. eg: | |
| * | |
| * `prune({ text:{ en:'foo', fr:'toto' }}, 'en') // -> { text:'foo' }` | |
| * `prune({ text:{ en:'foo', fr:'toto' }}, 'fr') // -> { text:'toto' }` | |
| * @param {object} target | |
| * @param {...string} autoKeys | |
| */ | |
| function prune(target, ...autoKeys) { | |
| if (target && typeof target === 'object') { | |
| for (const autoKey of autoKeys) { | |
| if (autoKey in target) { | |
| return prune(target[autoKey], ...autoKeys) | |
| } | |
| } | |
| const clone = Array.isArray(target) ? [] : {} | |
| for (const [key, value] of Object.entries(target)) { | |
| if (value && typeof value === 'object') { | |
| clone[key] = prune(value, ...autoKeys) | |
| } else { | |
| clone[key] = value | |
| } | |
| } | |
| return clone | |
| } | |
| return target | |
| } | |
| export { prune } | |
| export default prune |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage
output: