How to Generate Styles from Objects in JavaScript

How to Generate Styles from Objects in JavaScript

Ferenc Almasi β€’ 2020 October 13 β€’ πŸ“– 1 min read

To generate inline CSS styles from JavaScript objects, use the following function:

const book = {
  content: 'πŸ“’',
  display: 'block',
  padding: '20px',
  background: 'yellow'
};

const getStyles = obj => Object.keys(obj).map(key => `${key}:${obj[key]}`).join(';');

// Later you can call the function to inline the styles
getStyles(book);
getStyles.js
Copied to clipboard!

This works by:

  • First looping through the keys of the object with Object.keys
  • For each key, it returns with a new string (the key and value combined), by calling map
  • Lastly, it joins everything together with a semicolon, using join

If you have multiple styles to take care of, you can also use the below assignment to generate them in one go:

const styles = {
    heroCTA: {
        display: 'block'
    },
    heroImage: {
        display: 'block',
        width: '100%'
    }
};

const generatedStyles = Object.fromEntries(Object.entries(styles).map(([element, style]) => [element, getStyles(style)]));

// This will generate the following object:
{
    heroCTA: 'display:block',
    heroImage: 'display:block;width:100%'
}
getStyles.js
Copied to clipboard!
Generate Styles from Objects in JavaScript
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

Resources:

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended