Skip to content

Instantly share code, notes, and snippets.

@adrienZ
Last active September 28, 2020 09:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adrienZ/0257e37bf4788b903ba76fa82dac1ed1 to your computer and use it in GitHub Desktop.
Save adrienZ/0257e37bf4788b903ba76fa82dac1ed1 to your computer and use it in GitHub Desktop.
Convert a javascript object into a string of sass variables
/**
* @name jsToSassVariables
* @param {Object} obj
* @returns {String}
*/
function jsToSassVariables(obj) {
const { stringify, parse } = JSON
// remove null, undefined values and functions
const objStr = stringify(obj)
const objParsed = parse(objStr, (key, value) => {
if (key.length === 0) return value
// lists
if (Array.isArray(value)) {
return value.join(', ')
}
if (typeof value === 'number' || typeof value === 'boolean') {
return value.toString()
}
// object to sass map
if (value instanceof Object) {
let subkeys = '('
subkeys += Object.keys(value)
.map(subkey => `"${subkey}": ${value[subkey] || ''}`)
.join(', ')
subkeys += ')'
return subkeys
}
// default
return value
})
const objAsStrings = Object.keys(objParsed).map(varName => {
return `$${varName}: unquote(${JSON.stringify(objParsed[varName])})`
})
const resString = objAsStrings.join('; ') + ';'
return resString
}
module.exports = jsToSassVariables;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment