Reputation: 61
Say I have defined an array of object like so:
var person = [{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}, {firstName:"Arunima", lastName:"Ghosh", age:20, eyeColor:"black"}];
Now doing
console.log(person);
returns "[Object,Object]"
I want to print the details of the array. How do I do this?
Upvotes: 3
Views: 236
Reputation: 122908
Try this:
const something = JSON.stringify([
{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"},
{firstName:"Arunima", lastName:"Ghosh", age:20, eyeColor:"black"}
], null, " ");
document.querySelector("#result").textContent = something;
// or in the console
console.log(something);
<pre id="result"></pre>
Upvotes: 1
Reputation: 76436
As others already pointed out, you can use JSON.stringify
. However, your JSON shows Objects which are collapsable, so you have the information there. If you want to prettify your output further, you may try pretty-js or underscore.js.
Upvotes: 1
Reputation: 2536
var person = [{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}, {firstName:"Arunima", lastName:"Ghosh", age:20, eyeColor:"black"}] ;
console.log(JSON.stringify(person));
//if you want to parse
for (var i = 0; i < person.length; i++) {
var object = person[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
}
IS this what you want? If not please elaborate.
Upvotes: 2
Reputation: 2672
Try this: console.table(person);
This would print the object in tabular format which would be easy on the eyes. Result would look like this:
This is a lesser known feature compared to console.log but it is very handy at times.
Upvotes: 4
Reputation: 999
You can do this way:
var person = [{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"},
{firstName:"Arunima", lastName:"Ghosh", age:20, eyeColor:"black"}];
JSON.stringify(person);
Upvotes: 1