typescript 如何将对象作为 JSON 打印到 Angular2 中的控制台?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39047074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:46:06  来源:igfitidea点击:

How to print an object as JSON to console in Angular2?

jsonangulartypescript

提问by Bijith komalan

I'm using a service to load my form data into an array in my angular2 app. The data is stored like this:

我正在使用服务将我的表单数据加载到我的 angular2 应用程序中的数组中。数据存储如下:

arr = []
arr.push({title:name})

When I do a console.log(arr), it is shown as Object. What I need is to see it as [ { 'title':name } ]. How can I achieve that?

当我执行 a 时console.log(arr),它显示为 Object。我需要的是将其视为[ { 'title':name } ]. 我怎样才能做到这一点?

回答by Madhu Ranjan

you may use below,

你可以在下面使用,

  JSON.stringify({ data: arr}, null, 4);

this will nicely format your data with indentation.

这将使用缩进很好地格式化您的数据。

Hope this helps!!

希望这可以帮助!!

回答by Haifeng Zhang

To print out readable information. You can use console.table()which is much easier to read than JSON:

打印出可读信息。您可以使用console.table()比 JSON 更容易阅读的方法:

console.table(data);

This function takes one mandatory argument data, which must be an array or an object, and one additional optional parameter columns.

It logs data as a table. Each element in the array (or enumerable property if data is an object) will be a row in the table

该函数采用一个强制参数数据,它必须是一个数组或一个对象,以及一个额外的可选参数列。

它将数据记录为表格。数组中的每个元素(如果数据是对象,则为可枚举属性)将是表中的一行

Example: enter image description here

例子: 在此处输入图片说明

enter image description here

在此处输入图片说明

回答by BeetleJuice

You could log each element of the array separately

您可以分别记录数组的每个元素

arr.forEach(function(e){console.log(e)});

Since your array has just one element, this is the same as logging {'title':name}

由于您的数组只有一个元素,因此这与日志记录相同 {'title':name}

回答by mo sean

you can print any object

你可以打印任何对象

console.log(this.anyObject);

when you write

当你写

console.log('any object' + this.anyObject);

this will print

这将打印

any object [object Object]