[英]Print Object like console.log (with a lot of information) in javascript
I need to send an email that contains the console.log
output of a JS object.我需要发送一封包含 JS 对象的console.log
输出的电子邮件。 Here a code example:这是一个代码示例:
let array_multi = [];
array_multi["07:00"] = ["one","two","three"];
array_multi["08:00"] = ["foo","bar","foo"];
array_multi["09:00"] = ["lorem"];
console.log(array_multi);
In my console result like this:在我的控制台结果是这样的:
Is there some method to get this output in plain text, or should I write a custom parsing function?是否有某种方法可以以纯文本形式获取此输出,还是应该编写自定义解析函数?
If you are using JSON.stringify , you'll get the complete data, however there are a few downsides:如果您使用JSON.stringify ,您将获得完整的数据,但有一些缺点:
In your case you could do:在你的情况下,你可以这样做:
let array_multi = {}; array_multi["07:00"] = ["one","two","three"]; array_multi["08:00"] = ["foo","bar","foo"]; array_multi["09:00"] = ["lorem"]; // logs as object console.log(array_multi); console.log(typeof array_multi); // parse and convert to string console.log(JSON.stringify(array_multi)); console.log(typeof JSON.stringify(array_multi));
In Node.js you've got another option, which is util.format , which will return the same content as a string that you can see in the Node.js console.在 Node.js 中,您有另一个选项,即util.format ,它将返回与您可以在 Node.js 控制台中看到的字符串相同的内容。 While it does give you a great insight into the different datatypes and relationships, it cannot show you the same infinite tree that an interactive console is able to show, so it will only show you a small part of the big picture.虽然它确实让您深入了解不同的数据类型和关系,但它无法向您显示交互式控制台能够显示的相同无限树,因此它只能向您显示全局的一小部分。
¹: Your array_multi
should actually be an object, not an array, as arrays should only have numeric keys. ¹:你的array_multi
实际上应该是一个对象,而不是一个数组,因为数组应该只有数字键。
After a lot of search the right method is write a custom function (chrome have once inside dev tools core)经过大量搜索,正确的方法是编写自定义函数(chrome 在开发工具核心中有一次)
here the solution:这里的解决方案:
let array_multi = []; array_multi["07:00"] = ["one","two","three"]; array_multi["08:00"] = ["foo","bar","foo"]; array_multi["09:00"] = ["lorem"]; function print_js_element(elm, show_content = false){ let output_res = "{\\n"; let object_keys = Object.keys(elm); object_keys.some(function(key,index) { output_res += "\\t" + key + ": (" + elm[key].length + ")"; if(show_content){ output_res += " " + JSON.stringify(elm[key]); } output_res += "\\n"; }); output_res += "\\n}"; return output_res; } console.log(print_js_element(array_multi,false)); console.log(print_js_element(array_multi,true));
Covert this array into an object first:首先将此数组转换为对象:
let array_multi = []; array_multi["07:00"] = ["one","two","three"]; array_multi["08:00"] = ["foo","bar","foo"]; array_multi["09:00"] = ["lorem"]; let arrObj = {...array_multi}; console.log(JSON.stringify(arrObj));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.