Skip to content

Instantly share code, notes, and snippets.

@jniac
Last active September 25, 2020 09:35
Show Gist options
  • Select an option

  • Save jniac/39eabea6b06a9be5be348c11447c249c to your computer and use it in GitHub Desktop.

Select an option

Save jniac/39eabea6b06a9be5be348c11447c249c to your computer and use it in GitHub Desktop.
// 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
@jniac
Copy link
Author

jniac commented Jun 12, 2020

usage

someData = {
    name: {
        __DEV__:'foo',
        __PROD__:'Foo!',
    },
    info: {
        __DEV__: { message:'app is in development', aspect:'TBD' },
        __PROD__: { message:'that app is cool', aspect: { __MOBILE__:'9/16', __TABLET__:'4/3', __DESKTOP__:'16/9' } },
    },
}

prune(someData, '__PROD__', '__TABLET__')

output:

{
    name: "Foo!",
    info: {  message:"that app is cool", aspect:"4/3" },
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment