83

I have created an object array in JavaScript. How can I print the object array in the browser window, similar to print_r function in PHP?

var lineChartData = [{
            date: new Date(2009, 10, 2),
            value: 5
        }, {
            date: new Date(2009, 10, 25),
            value: 30
        }, {
            date: new Date(2009, 10, 26),
            value: 72,
            customBullet: "images/redstar.png"
        }];
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Vinod Kumar
  • 1,479
  • 3
  • 13
  • 23
  • 11
    Use `console.log(lineChartData)` to log it to the console. – Rob Feb 15 '13 at 13:01
  • 3
    You can use `console.debug(lineChartData)` to see the object in the console. (In firefox: Tools->Web Developer->Web Console (or Ctrl+Shift+K) - Or download [Firebug](https://getfirebug.com/) – Adam Tomat Feb 15 '13 at 13:03

13 Answers13

143

Simply stringify your object and assign it to the innerHTML of an element of your choice.

yourContainer.innerHTML = JSON.stringify(lineChartData);

If you want something prettier, do

yourContainer.innerHTML = JSON.stringify(lineChartData, null, 4);

var lineChartData = [{
            date: new Date(2009, 10, 2),
            value: 5
        }, {
            date: new Date(2009, 10, 25),
            value: 30
        }, {
            date: new Date(2009, 10, 26),
            value: 72,
            customBullet: "images/redstar.png"
        }];

document.getElementById("whereToPrint").innerHTML = JSON.stringify(lineChartData, null, 4);
<pre id="whereToPrint"></pre>

But if you just do this in order to debug, then you'd better use the console with console.log(lineChartData).

Christoph
  • 50,121
  • 21
  • 99
  • 128
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • If I do this in bash, is there a way to pretty print in console? – giorgio79 Apr 03 '21 at 17:55
  • @denys-séguret What I did was like: `prevElement = document.createElement("prev");` Then append to the html body with innerHtml set to the above stringified string. Although I can see the `prev` element was created successfully, but the JSON is still not pretty printed as I want. Could you help me understand why? – Dreamer Jun 22 '21 at 15:37
32

Did you check

console.table(yourArray);

More infos here: https://developer.mozilla.org/en-US/docs/Web/API/Console/table

charlesdg
  • 814
  • 11
  • 18
14

If you are using Chrome, you could also use

console.log( yourArray );
Toto-Graph
  • 184
  • 5
7

There is a wonderful print_r implementation for JavaScript in php.js library.

Note, you should also add echo support in the code.

DEMO: http://jsbin.com/esexiw/1

VisioN
  • 143,310
  • 32
  • 282
  • 281
  • 14
    seriously, the `console` is a better place for debug info than the main browser window. – SDC Feb 15 '13 at 13:20
  • @SDC Well I admit this is true, sometimes you make an http request which returns over 100 or more objects and it doesn't make sense to click the arrow and open them all to see what's inside of the array of objects – DrewT Jan 13 '16 at 19:57
3

Simple function to alert contents of an object or an array .
Call this function with an array or string or an object it alerts the contents.

Function

function print_r(printthis, returnoutput) {
    var output = '';

    if($.isArray(printthis) || typeof(printthis) == 'object') {
        for(var i in printthis) {
            output += i + ' : ' + print_r(printthis[i], true) + '\n';
        }
    }else {
        output += printthis;
    }
    if(returnoutput && returnoutput == true) {
        return output;
    }else {
        alert(output);
    }
}

Usage

var data = [1, 2, 3, 4];
print_r(data);
Rayiez
  • 1,420
  • 19
  • 20
1
document.getElementById('container').innerHTML = lineChartData[array_index]
Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
bhupesh
  • 25
  • 6
1

you can use console.log() to print object

console.log(my_object_array);

in case you have big object and want to print some of its values then you can use this custom function to print array in console

this.print = function (data,bpoint=0) {
    var c = 0;
    for(var k=0; k<data.length; k++){
        c++;
        console.log(c+'  '+data[k]);
        if(k!=0 && bpoint === k)break;  
    }
}

usage

print(array);   // to print entire obj array

or

print(array,50);  // 50 value to print only 
user889030
  • 4,353
  • 3
  • 48
  • 51
  • This code pulled up the 'print to actual paper' dialog window. Don't know if that was the intended outcome - but that's what happened for me when I ran it on Brave. – Radu Bartan Mar 18 '22 at 12:17
0

I use the below function to display a readout in firefox console log:

////        make printable string for console readout, recursively
var make_printable_object = function(ar_use)
{
////        internal arguments
var in_tab = arguments[1];
var st_return = arguments[2];
////        default vales when applicable
if (!in_tab) in_tab = 0;
if (!st_return) st_return = "";
////        add depth
var st_tab = "";
for (var i=0; i < in_tab; i++) st_tab = st_tab+"-~-~-";

////        traverse given depth and build string
for (var key in ar_use)
{
    ////        gather return type
    var st_returnType = typeof ar_use[key];
    ////        get current depth display
    var st_returnPrime = st_tab+ "["+key+"] ->"+ar_use[key]+"< is {"+st_returnType+"}";
    ////        remove linefeeds to avoid printout confusion
    st_returnPrime = st_returnPrime.replace(/(\r\n|\n|\r)/gm,"");
    ////        add line feed
    st_return = st_return+st_returnPrime+"\n";
    ////         stop at a depth of 15
    if (in_tab>15) return st_return;
    ////        if current value is an object call this function
    if ( (typeof ar_use[key] == "object") & (ar_use[key] != "null") & (ar_use[key] != null) ) st_return = make_printable_object(ar_use[key], in_tab+1, st_return);


}

////        return complete output
return st_return;

};

Example:

console.log( make_printable_object( some_object ) );

Alternatively, you can just replace:

st_return = st_return+st_returnPrime+"\n";

with

st_return = st_return+st_returnPrime+"<br/>";

to print out in a html page.

Shawn
  • 1
  • 2
0

You can just use the following syntax and the object will be fully shown in the console:

console.log('object evt: %O', object);

I use Chrome browser don't know if this is adaptable for other browsers.

Torsten Barthel
  • 3,059
  • 1
  • 26
  • 22
0

Emm... Why not to use something like this?

function displayArrayObjects(arrayObjects) {
        var len = arrayObjects.length, text = "";

        for (var i = 0; i < len; i++) {
            var myObject = arrayObjects[i];
            
            for (var x in myObject) {
                text += ( x + ": " + myObject[x] + " ");
            }
            text += "<br/>";
        }

        document.getElementById("message").innerHTML = text;
    }
            
            
            var lineChartData = [{
                date: new Date(2009, 10, 2),
                value: 5
            }, {
                date: new Date(2009, 10, 25),
                value: 30
            }, {
                date: new Date(2009, 10, 26),
                value: 72,
                customBullet: "images/redstar.png"
            }];

            displayArrayObjects(lineChartData);
<h4 id="message"></h4>

result:

date: Mon Nov 02 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 5 
date: Wed Nov 25 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 30 
date: Thu Nov 26 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 72 customBullet: images/redstar.png 

jsfiddle

Gennady G
  • 996
  • 2
  • 11
  • 28
0

The question is: How to print object array in JavaScript? To print one use this.

document.write(array[i])

Will print one item where i is the array count starting at 0.

document.write(array)

Will print all of them.

ACKmiecik
  • 70
  • 8
0

While this doesn't answer the question specifically in terms of a JS function similar to print_r, it doesn't require a lot of setup to get it working and displaying data in an easy-on-the-eyes format.

The inspiration for this solution

const result = document.getElementById('result');
const lineChartData = [
  {
    date: "2009-10-2",
    value: 5
  },
  {
    date: "2009-10-25",
    value: 30
  },
  {
    date: "2009-10-26",
    value: 72
  }
];

function funCall() {
  let html = `<table border='1|1' cellpadding='2' cellspacing='0'>
              <tr>
              <th>Date</th>
              <th>Value</th>
              </tr>`;

  setTimeout(() => {
    for (let i = 0; i < lineChartData.length; i++) {
      html += `<tr>
                <td>${lineChartData[i].date}</td>
                <td>${lineChartData[i].value}</td>
               </tr>`;
    }
    result.innerHTML = html;
  }, 500);
}
funCall();
* {
  box-sizing: border-box;
  font-family: sans-serif;
  font-size: 0.9rem;
}
table {
  width: 150px;
  margin: 0 auto;
}
th {
  background: #654789;
  color: #fff;
}
tr:nth-of-type(odd) {
  background: #eee;
}
th,
td {
  text-align: center;
}
<div id="result"></div>
Realto619
  • 83
  • 2
  • 7
-1

Not sure about the subelements, but all browsers should support this now:

for (val of lineChartData) {
  document.write(val);
}

This might give you some ideas For-each over an array in JavaScript?

PJ Brunet
  • 3,615
  • 40
  • 37
  • Recommending `document.write` without any context is a very bad idea, since it's writing to the stream, which would destroy a closed document (fully loaded page). The `for ... of` loop is a nice idea though. Please give more context or change the `document.write`. – Christoph Nov 28 '18 at 15:23
  • @Christoph You're free to expand and make edits. The nuances of progressive rendering and DOM manipulation, there are great videos about that on YouTube, but that's getting way off the topic. I find document.write is often faster and more convenient than console.log for quick tests, and uses less screen real estate, but it depends what you're building and of course your personal preferences. – PJ Brunet Nov 29 '18 at 22:09