
How to Generate Styles from Objects in JavaScript
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);
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%'
}
Copied to clipboard!

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

Resources:
π More Webtips
Master the Art of Frontend
Unlimited access to hundred of tutorials
Access to exclusive interactive lessons
Remove ads to learn without distractions