11

I'm using a lot console.log for debugging purpose. When I log long objects, it is difficult to read the complete object. Is there a console.pretty or something to print the data in a pretty way?

Actual (logs inline):
{data:'data',data1:'data1'}

Expect:

{
  data:'data',
  data1:'data1'
}
0

1 Answer 1

30

You can use JSON.stringify.

The third parameter passed will be the number of spaces to indent the members.

var obj = {
  data: 'data',
  data1: 'data1'
};

console.log(JSON.stringify(obj, 0, 2));


If you need this more often, you can also define a function on window object

// Define on global window object
window.console.prettyPrint = function() {
  // Loop over arguments, so any number of objects can be passed
  for (var i = 0; i < arguments.length; i++) {
    console.log(JSON.stringify(arguments[i], 0, 2));
  }
};

var obj = {
  data: 'data',
  data1: 'data1'
};

var myObj = {
  hello: 'World!'
};

console.prettyPrint(obj, myObj);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.