How to display all inputs of an array of objects in Javascript?
Let's say I have defined an object array like this:
var person = [{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}, {firstName:"Arunima", lastName:"Ghosh", age:20, eyeColor:"black"}];
Now let's do
console.log(person);
returns "[Object,Object]"
I want to print the details of an array. How to do it?
+3
source to share
6 answers
As others have pointed out, you can use JSON.stringify
. However, your JSON is showing objects being dumped, so you have the information. If you want to refine your output even further, you can try pretty-js or underscore.js .
+1
source to share
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 clarify.
+2
source to share
Try the following:
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>
+1
source to share