Javascript [object Object] to string

I'll start with a small background.

What I'm trying to do is capture the "style" attribute from an element, and ultimately it can be displayed in a text box (dynamic styling). With this, I create the css prefix because I only capture computed styles.

With this, I have a variable with a bunch of css properties, as shown here:

compcss = {
                'font-size': fsize,
                'padding': tpadd,

                '-webkit-border-radius': brad,
                '-moz-border-radius': brad,
                '-o-border-radius': brad,
                '-ms-border-radius': brad,
                'border-radius': brad,

                'background': bground,
                'background-m': bgmoz,
                'background-o': bgop,
                'background-i': bgie,
                'color': 'white',
                'text-shadow': '0 -1px 0 rgba(0, 0, 0, 0.25)',
                'text-decoration': 'none',
                'border': '1px solid rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25)',

            };

Usually fsize, tpadd, brad and bground are filled

document.defaultView.getComputedStyle(cssStr[0], "")[style]

but for the next jsbin i put static numbers.

This is returned as [object Object]if registering or typing in a text field, as you would expect. However, I want this object to output as a string in the form:

font-size: Xpx;
padding: Ypx;
-webkit-border-radius: Zpx;

etc., I tried JSON.stringify (compcss), but it returns as:

"font-fize":"Xpx","padding":"Ypx","-webkit-border-radius":"Zpx"

to the end of the line.

, ? , - . ?

jsbin, : http://jsbin.com/opiwuy/2/edit

Vanilla Javascript, JQuery .

!

+5
3
  var value = '';
  $.each(compcss, function(key, val) {
    value += key + ' : ' + val + ';' +'\n';
  });
  $('#css').val(value);

DEMO

$('#css').val(function() {
    var value = '';
    $.each(compcss, function(key, val) {
      value += key + ' : ' + val + ';' + '\n';
    });
    return value;
});

DEMO

+5

- , , :

function cssStringify(myObject) {
    var result = "";
    var stringObjs = JSON.stringify(myObject).split(",");
    $.each(stringObjs, function(val) {
        var pair = val.split(":");
        result = result + pair[0] + ":" + pair[1] + ";\n";
    });
    return result;
}
+2

Just throwing my version with .replace

var xx = JSON.stringify(compcss); 
$('#csjson').val(
    xx.replace(/":"|":/g, ":")
      .replace(/,"/g, "\n")
      .replace(/"/g, ""));

DEMO: http://jsbin.com/opiwuy/4

+2
source

All Articles