How to Generate Styles from Objects in 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);
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%'
}
Resources:
π More Webtips
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: