JSlearner
JSlearner

Reputation: 61

How to display all the inputs of an array of objects in Javascript?

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

Answers (6)

KooiInc
KooiInc

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

Lajos Arpad
Lajos Arpad

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

Sachin Bahukhandi
Sachin Bahukhandi

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

Pankaj Shukla
Pankaj Shukla

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: enter image description here

This is a lesser known feature compared to console.log but it is very handy at times.

Upvotes: 4

anis programmer
anis programmer

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

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

console.log(JSON.stringify(person));

That's one way to do it.

Upvotes: 3

Related Questions