console.log showing contents of array object
Asked Answered
A

7

77

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?

Ariadne answered 27/10, 2011 at 6:56 Comment(12)
What browser are you using? The console object is only available on certain browsers or add-onsKnickerbockers
works for me: jsfiddle.net/PxZjrAggravate
Im using IE 8 there is no alert meesage box that appearsAriadne
console.log is only available to firebug as a standalone debugger which is what you would have to use in your case with IE8. or to WebKit browsers as part of their inspectors which would include Chrome, Safari, and Opera. Your code works fine in all of those for me.Maestricht
so @ryanOptini how do print out the contents of my array to show in a dialog I thought that was what console.log was for.Ariadne
alert(filters); in IE8 should bring up a dialogMaestricht
to see console.log(filters) (responding to your comment below), in google chrome right click on the page and hit inspect, then go to the bottom left and hit show console. Once you activate the function that has your console.log in it you will see a print out of the current state of filters.Maestricht
I understand a bit more now aboput console.logAriadne
How do i write out the array int a div in a json string formatAriadne
@ryanOptini — Opera uses Presto, not WebKit. It does have console.log, but via Dragonfly, not the WebKit inspector.Eiger
@Quentin, my bad sorta late where I am but your rightMaestricht
@KDM - console.log messages will appear in the "Console" right-side window for the "Script" Tab in IE Developer Tools debugger. You need to visit the web-page to be debugged, hit F12 key to activate the debugger. Select "Start Debugging" and then choose the "Script" Tab.Destefano
D
12

console.log does not produce any message box. I don't think it is available in any version of IE (nor Firefox) without the addition of firebug or some equivalent.

It is however available in Safari and Chrome. Since you mention Chrome I'll use that for my example.

You'll need to open your window and its developer window counterpart. you can do this by right clicking any element on the page and selecting "Inspect element". your window will be divided in two parts, the developer part being the bottom. in the division between the two parts is a bar with buttons and the rightmost button there is labeled "console". You'll need to click that to switch to the console tab. Press F12 for developer tools in most browsers on Windows, command + shift + I on macOS.

Once there, you will be able to interact with whatever page is loaded on top through javascript from that console, and any messages you console.log will be displayed there.

Duteous answered 27/10, 2011 at 8:3 Comment(3)
You'll need to (install and) activate IE Developer Tools debugger. Just go to the web-page to debug and hit the F12 button to activate the debugger. This defines the console thingy you use in your code.Destefano
@GuruM: This doesn't will only write out the object and not the contents of the object like it does in FireFox or Chrome.Gondola
@NeilKnight. The questioner can use the techniques specified elsewhere in this page to look that up. I was just informing him how he could activate the IE debugger. Kris had not mentioned how to get the debugger open in IE, so just filling the gap.Destefano
D
110

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"
  }
 ]
}"
Deenadeenya answered 13/5, 2012 at 12:25 Comment(1)
I propose somebody fixes it in a future version of Javascript and makes objects automatically convert to a sensible string representation by default. Probably nobody wants to see Object[Object].Skeie
A
27

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 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'.

This statements also work in a NodeJS environment. The output then goes to std out per default. That is e.g. the terminal where the NodeJS process is running.

NodeJS console.log calls don't print full object tress. Instead sub objects are printed as [Object object]. To see full objects in the output you have to use util.inspect like so:

console.log(util.inspect(object, true, 10))
Alenealenson answered 10/3, 2016 at 14:41 Comment(2)
console.table( object ) was a great idea thanksBureaucrat
console.table ftwGownsman
D
12

console.log does not produce any message box. I don't think it is available in any version of IE (nor Firefox) without the addition of firebug or some equivalent.

It is however available in Safari and Chrome. Since you mention Chrome I'll use that for my example.

You'll need to open your window and its developer window counterpart. you can do this by right clicking any element on the page and selecting "Inspect element". your window will be divided in two parts, the developer part being the bottom. in the division between the two parts is a bar with buttons and the rightmost button there is labeled "console". You'll need to click that to switch to the console tab. Press F12 for developer tools in most browsers on Windows, command + shift + I on macOS.

Once there, you will be able to interact with whatever page is loaded on top through javascript from that console, and any messages you console.log will be displayed there.

Duteous answered 27/10, 2011 at 8:3 Comment(3)
You'll need to (install and) activate IE Developer Tools debugger. Just go to the web-page to debug and hit the F12 button to activate the debugger. This defines the console thingy you use in your code.Destefano
@GuruM: This doesn't will only write out the object and not the contents of the object like it does in FireFox or Chrome.Gondola
@NeilKnight. The questioner can use the techniques specified elsewhere in this page to look that up. I was just informing him how he could activate the IE debugger. Kris had not mentioned how to get the debugger open in IE, so just filling the gap.Destefano
W
3

The console object is available in Internet Explorer 8 or newer, but only if you open the Developer Tools window by pressing F12 or via the menu.

It stays available even if you close the Developer Tools window again until you close your IE.

Chorme and Opera always have an available console, at least in the current versions. Firefox has a console when using Firebug, but it may also provide one without Firebug.

In any case it is a save approach to make the use of console output optional. Here are some examples on how to do that:

if (console) {
    console.log('Hello World!');
}

if (console) console.debug('value of someVar: ' + someVar);
Wysocki answered 27/10, 2011 at 8:44 Comment(1)
I never heard of that approach and personally think its a bit unhandy when just debugging some code. When using a bundler (like Angular is using Webpack as bundler) your code will be processed anyway and all the log statements will be eliminated.Alenealenson
E
1

Seems like Firebug or whatever Debugger you are using, is not initialized properly. Are you sure Firebug is fully initialized when you try to access the console.log()-method? Check the Console-Tab (if it's set to activated).

Another possibility could be, that you overwrite the console-Object yourself anywhere in the code.

Evildoer answered 27/10, 2011 at 6:59 Comment(2)
Im using cosole.log in IE8 and google chrome Im not getting any results is it some setting in the browser I use.Ariadne
@KDM - console.log messages will appear in the "Console" right-side window for the "Script" Tab in IE Developer Tools debugger. You need to visit the web-page to be debugged, hit F12 key to activate the debugger. Select "Start Debugging" and then choose the "Script" Tab. Run the script to see the log messages in the "Console" window.Destefano
M
1

Json stands for JavaScript Object Notation really all json is are javascript objects so your array is in json form already. To write it out in a div you could do a bunch of things one of the easiest I think would be:

 objectDiv.innerHTML = filter;

where objectDiv is the div you want selected from the DOM using jquery. If you wanted to list parts of the array out you could access them since it is a javascript object like so:

 objectDiv.innerHTML = filter.dvals.valueToDisplay; //brand or count depending.

edit: anything you want to be a string but is not currently (which is rare javascript treats almost everything as a string) just use the toString() function built in. so line above if you needed it would be filter.dvals.valueToDisplay.toString();

second edit to clarify: this answer is in response to the OP's comments and not completely to his original question.

Maestricht answered 27/10, 2011 at 7:54 Comment(0)
L
1

I warmly recommend this snippet to ensure, accidentally left code pieces don't fail on clients browsers:

/* neutralize absence of firebug */
if ((typeof console) !== 'object' || (typeof console.info) !== 'function') {
    window.console = {};
    window.console.info = window.console.log = window.console.warn = function(msg) {};
    window.console.trace = window.console.error = window.console.assert = function(msg) {};
}

rather than defining an empty function, this snippet is also a good starting point for rolling your own console surrogate if needed, i.e. dumping those infos into a .debug Container, show alerts (could get plenty) or such...

If you do use firefox+firebug, console.dir() is best for dumping array output, see here.

Linguini answered 4/7, 2013 at 11:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.