Skip to content

Instantly share code, notes, and snippets.

@illepic
Last active November 5, 2023 14:54
Show Gist options
  • Save illepic/49ec49243c73a58c996a929af8ca9dd8 to your computer and use it in GitHub Desktop.
Save illepic/49ec49243c73a58c996a929af8ca9dd8 to your computer and use it in GitHub Desktop.
Javascript object to Sass map transform
// 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