简体   繁体   English

如何在Javascript中显示对象数组的所有输入?

[英]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? 我该怎么做呢?

Try this: console.table(person); 试试这个: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. 与console.log相比,这是一个鲜为人知的功能,但它有时非常方便。

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

这是一种方法。

 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. 如果没有请详细说明。

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> 

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

As others already pointed out, you can use JSON.stringify . 正如其他人已经指出的那样,您可以使用JSON.stringify However, your JSON shows Objects which are collapsable, so you have the information there. 但是,您的JSON显示可折叠的对象,因此您可以在那里获得信息。 If you want to prettify your output further, you may try pretty-js or underscore.js . 如果你想进一步美化你的输出,你可以试试pretty-jsunderscore.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM