Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print object array in JavaScript?

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"         }]; 
like image 878
Vinod Kumar Avatar asked Feb 15 '13 13:02

Vinod Kumar


People also ask

How do you print an array in JavaScript?

To print an array of objects properly, you need to format the array as a JSON string using JSON. stringify() method and attach the string to a <pre> tag in your HTML page. And that's how you can print JavaScript array elements to the web page.

How can I print object in JavaScript?

stringify() method is used to print the JavaScript object. JSON. stringify() Method: The JSON. stringify() method is used to allow to take a JavaScript object or Array and create a JSON string out of it.

How do you display an object inside an array?

You can just use the following syntax and the object will be fully shown in the console: console. log('object evt: %O', object);


1 Answers

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).

like image 120
Denys Séguret Avatar answered Oct 02 '22 17:10

Denys Séguret