I have tried using console.log
so I can see the content of my array that contains multiple objects. However I get an error saying console.log
is not an object etc. I'm using jquery 1.6.2 and my array is like this:
filters = {dvals:[{'brand':'1', 'count':'1'}, {'brand':'2', 'count':'2'}, {'brand':'3', 'count':'3'}]} console.log(filters);
What I want to to do is write out the contents of array(filters)
to an alert box (that's what I thought console.log
did) in the filters format. How do I do that?
log(JSON. stringify(obj)) method can be useful for logging the object to the console as string, as long as the data in the object is JSON-safe. For complex objects, the method Object. entries(obj) is a way of looping through an object that can be used to log the object to the console.
Answer: Use console. log() or JSON. stringify() Method log() method, if you simply wants to know what's inside an object for debugging purpose. This method will print the object in browser console.
Just pass the Array object into a console. log() to print the array as comma-separated in JavaScript. And if you want to print array elements wise then use loop (while or for-loop).
there are two potential simple solutions to dumping an array as string. Depending on the environment you're using:
…with modern browsers use JSON:
JSON.stringify(filters); // returns this "{"dvals":[{"brand":"1","count":"1"},{"brand":"2","count":"2"},{"brand":"3","count":"3"}]}"
…with something like node.js you can use console.info()
console.info(filters); // will output: { dvals: [ { brand: '1', count: '1' }, { brand: '2', count: '2' }, { brand: '3', count: '3' } ] }
Edit:
JSON.stringify comes with two more optional parameters. The third "spaces" parameter enables pretty printing:
JSON.stringify( obj, // the object to stringify replacer, // a function or array transforming the result spaces // prettyprint indentation spaces )
example:
JSON.stringify(filters, null, " "); // returns this "{ "dvals": [ { "brand": "1", "count": "1" }, { "brand": "2", "count": "2" }, { "brand": "3", "count": "3" } ] }"
It's simple to print an object to console in Javascript. Just use the following syntax:
console.log( object );
or
console.log('object: %O', object );
A relatively unknown method is following which prints an object or array to the console as table:
console.table( object );
I think it is important to say that this kind of logging statement only works inside a browser environment. I used this with Google Chrome. You can watch the output of your console.log calls inside the Developer Console: Open it by right click on any element in the webpage and select 'Inspect'. Select tab 'Console'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With