javascript [object Object] to string

html, javascript, jquery, json

Solution

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

DEMO

You can also do

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

DEMO

Problem

I'll start with a little background. So what I'm trying to do is grabbing the "style" attribute from an element, and the eventual plan is to output it to a text box (the styling is dynamic). With this I'm creating some css prefixing, due to the fact that I'm only grabing computed styles. With that, I have a variable with a bunch of css properties as seen 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)', }; ``` Normally fsize, tpadd, brad, and bground are filled with ``` document.defaultView.getComputedStyle(cssStr[0], "")[style] ``` but for the following jsbin I put in static numbers. This returns as `[object Object]` when logged or put into the text box, which is to be expected. However, I wish to get this object outputting as a string in the form: ``` font-size: Xpx; padding: Ypx; -webkit-border-radius: Zpx; ``` and so on, I've tried JSON.stringify(compcss), but that returns as: ``` "font-fize":"Xpx","padding":"Ypx","-webkit-border-radius":"Zpx" ``` all the way down the line. What is the best way to get this to output the way I want? Let me know if anything needs clarifying. Is there a better way of going about this? here's a jsbin for example: http://jsbin.com/opiwuy/2/edit Both Vanilla Javascript and JQuery are fine. Thanks!

Original source