Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery quickly dump object's members

I was wondering if there was a quick way to get all of an object's variable's values, similar to php's var_dump() method.

So if I had an object

var myObject = {
    Up: 38,
    Dn: 40,
    Lf: 37,
    Rt: 39,
    Enter: 13,
    Space: 32,
    Esc: 27
};

The string I would get back would look something like

[ Up:38, Dn:40, Lf:37, Rt:39, Enter:13, Space:32, Esc:27 ]

Let's say I need to do this on a computer where I can't use firebug. Is there any way to do this without iterating through all the parameters in an object? Is there a standalone library that has something like this?

like image 264
Hans Z Avatar asked Jun 13 '12 21:06

Hans Z


Video Answer


3 Answers

As a quick one liner I often use

   var o = {a:1, b:2}, k, s = []; for (k in o) o.hasOwnProperty(k) && s.push (o[k]); s = s.join (', ');

You only need to change one occurence of the object (value of o) and the result is in s.

This does not recurse into the data structure. JSON.stringify is probably more suited if that is a requirement. Note however that JSON.stringify does not do functions, it simply skips them!

For formatted stringify use

JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces

As per answer to Javascript: How to generate formatted easy-to-read JSON straight from an object?

like image 112
HBP Avatar answered Oct 18 '22 18:10

HBP


Using the default dev. tools on IE, Chrome and Firefox

console.dir(myObject); 

If you really can't use these tools then maybe a JSON.stringify(myObject) could help.

like image 31
Ryan Avatar answered Oct 18 '22 19:10

Ryan


Have you tried FirebugLite ? It has a lot of Firebug functions.

This is Javascript Firebug library, you need only to load script

<script type="text/javascript" src="https://getfirebug.com/firebug-lite.js"></script>

And you will get Firebug console in all major browsers including Internet Explorer

like image 2
Slawek Avatar answered Oct 18 '22 20:10

Slawek