Reputation: 11822
Is there any method or way to check what is inside a JavaScript object. something like print_r
in PHP?
Cheers
Upvotes: 4
Views: 11269
Reputation: 12215
Best trick for me:
console.dir(yourobject);
See it live in your chrome dev tools. You can pass in any object to find out what's inside of it a swell. Very helpful
Upvotes: 3
Reputation: 8443
If you use Mozilla Firefox, you can use Firebug. To see what your variable or object is, do it like code below (for example, I use JSON variable)
var yourObject = {test: 'this is just a test'};
console.log(yourObject);
After you install Firebug, run your html file that contains this javascript and choose Console tab in Firebug. You will see the result there. Hope this helps you. :)
Upvotes: 3
Reputation: 344521
Consider the following object:
var x = {
property1: 'value1',
property2: 'value2',
property3: 'value3',
method1: function () {
return 0;
},
method2: function () {
return 0;
}
};
Then doing:
for (var prop in x) {
console.log(prop);
}
Outputs:
property1
property2
property3
method1
method2
You may want to use the hasOwnProperty()
method to ensure that you do not get properties from the object's prototype chain:
for (var prop in x) {
if (x.hasOwnProperty(prop)) {
console.log(prop);
}
}
Upvotes: 1
Reputation: 21727
Install FireBug. Its a plug-in for Mozilla Firefox.
In your source file, write: console.log(yourObjectGoesHere);
and go to the "console" tab in FireBug... Killer object discovery, presented in an easy-to-grasp tree-format.
Upvotes: 0
Reputation: 61617
Javascript objects are esentially maps of key/value pairs. You can access members through both dot notation (e.g. myObject.someProp
), or even through index notation (myObject["someProp"]
). The use of the latter will probably help you:
function print(obj) {
for (var i in obj)
console.log(i + " - " + obj[i]);
}
}
Run that through Firebug and see what you get :)
Upvotes: 4
Reputation: 24472
Use this custom function or JSON.stringify(obj);
/**
* Gets the string representation of the specified object. This method is
* used for debugging
* @param {Object} Object to convert to string
* @return {String} The string representation of the object
*/
var toObjectSource = function(obj) {
if(obj === null) {
return "[null]";
}
if(obj === undefined) {
return "[undefined]";
}
var str = "[";
var member = null;
for(var each in obj) {
try {
member = obj[each];
str += each + "=" + member + ", ";
}catch(err) {
alert(err);
}
}
return str + "]";
}
Upvotes: 4
Reputation: 13438
Use Firebug for Firefox or Developer Tools for Google Chrome/Safari to inspect your objects. It's the best way to do it in my opinion.
Upvotes: 10