How to Generate Styles from Objects in JavaScript

How to Generate Styles from Objects in JavaScript

Ferenc Almasi β€’ 2020 October 13 β€’ Read time 1 min read
  • twitter
  • facebook
JavaScript

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

Copied to clipboard! Playground
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

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:

Copied to clipboard! Playground
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
Generate Styles from Objects in JavaScript
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.