Skip to content

Instantly share code, notes, and snippets.

@ezakto
Forked from 140bytes/LICENSE.txt
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ezakto/e6728325a2376244d564 to your computer and use it in GitHub Desktop.
Save ezakto/e6728325a2376244d564 to your computer and use it in GitHub Desktop.
CSS-like plain objects to CSS strings
function(
a, // CSS-like plain object
b, // Result string
c, // Selector key
d // Property key
){
b=''; // Initialize result
for(c in a){ // Loop through the rules
b+=c+'{'; // Append selector and open rule's property listing
for(d in a[c]) // Loop through properties
b+=d+':'+a[c][d]+';'; // Append property:value;
b+='}' // Close rule
}
return b // There you go
}
function(a,b,c,d){b='';for(c in a){b+=c+'{';for(d in a[c])b+=d+':'+a[c][d]+';';b+='}'}return b}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2015 Nicolás Arias <nicolas@nicolasarias.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "JSON2CSS",
"description": "Convert CSS-like plain objects into CSS strings",
"keywords": [
"css",
"object"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>.selector{line-height:16px;color:red;}#selector{height:300px;}</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var css = {
".selector": {
"line-height": "16px",
"color": "red"
},
"#selector": {
"height": "300px"
}
}
var myFunction = function(a,b,c,d){b='';for(c in a){b+=c+'{';for(d in a[c])b+=d+':'+a[c][d]+';';b+='}'}return b}
document.getElementById( "ret" ).innerHTML = myFunction(css)
</script>
@atk
Copy link

atk commented Jul 9, 2015

How about using recursion and abusing the fact that strings have a (deprecated) big method?

function c(a,b,d){d=d||'';for(b in a)d+=a[b].big?b+':'+a[b]+';':b+'{'+c(a[b])+'}';return d}

@ezakto
Copy link
Author

ezakto commented Jul 10, 2015

@atk awesome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment