Bijith komalan
Bijith komalan

Reputation: 163

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

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

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?

Upvotes: 9

Views: 25166

Answers (6)

Mathew V Manoj
Mathew V Manoj

Reputation: 31

Please try using the JSON Pipe operator in the HTML file. As the JSON info was needed only for debugging purposes, this method was suitable for me. Sample given below:

<p>{{arr | json}}</p>

Upvotes: 0

Sahil Sharma
Sahil Sharma

Reputation: 156

first convert your JSON string to Object using .parse() method and then you can print it in console using console.table('parsed sring goes here').

e.g.

const data = JSON.parse(jsonString);
console.table(data);

Upvotes: 0

Madhu Ranjan
Madhu Ranjan

Reputation: 17894

you may use below,

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

this will nicely format your data with indentation.

Upvotes: 14

Haifeng Zhang
Haifeng Zhang

Reputation: 31895

To print out readable information. You can use console.table() which is much easier to read than 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

Upvotes: 2

Mohsin AR
Mohsin AR

Reputation: 3108

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]

Upvotes: -2

BeetleJuice
BeetleJuice

Reputation: 40886

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}

Upvotes: -1

Related Questions