Skip to content

Instantly share code, notes, and snippets.

@stowball
Created March 31, 2021 01:21
Show Gist options
  • Save stowball/631a4ef0a87e01c92ab115ef889d0af6 to your computer and use it in GitHub Desktop.
Save stowball/631a4ef0a87e01c92ab115ef889d0af6 to your computer and use it in GitHub Desktop.
Convert an object to custom properties with refs
// Adapted from https://stackoverflow.com/a/53620876/1390770
const convertObjectToCustomProperties = obj => {
const isLeaf = val => typeof val === 'string';
const addDelimiter = (head, key) => (head ? `${head}-${key}` : key);
const paths = (pathObj = {}, head = '') => {
return Object.entries(pathObj).reduce((product, [key, value]) => {
const path = addDelimiter(head, key);
return isLeaf(value)
? product.concat(`--${path}: ${value}`, `--${path}-ref: var(--${path})`)
: product.concat(paths(value, path));
}, []);
};
return paths(obj).join(';\n');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment