Last active
November 5, 2023 14:54
-
-
Save illepic/49ec49243c73a58c996a929af8ca9dd8 to your computer and use it in GitHub Desktop.
Javascript object to Sass map transform
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
// For a JS object like so | |
const sassMapObj = { | |
namespace: { | |
primary: { | |
white: '#fff', | |
}, | |
secondary: { | |
black: '#000', | |
}, | |
}, | |
}; | |
// Recursively build out the sass map syntax based on the sassMapObj | |
const drill = (obj) => | |
Object.entries(obj).reduce((acc, [key, value]) => { | |
acc += | |
typeof value === 'string' | |
? `'${key}': ${value},` | |
: `'${key}': (${drill(value)}),`; | |
return acc; | |
}, ''); | |
const sassMapString = `$tokens: (${drill(sassMapObj)});`; | |
// Results in this string (unformatted, use prettier to make pretty or something): | |
// | |
// $tokens: ( | |
// 'namespace': ( | |
// 'primary': ( | |
// 'white': '#fff', | |
// ), | |
// 'secondary: ( | |
// 'black': '#000', | |
// ), | |
// ), | |
// ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment