But I'm used to seeing its properties and its values, too, like in the Google Chrome Developer Console.
So I wrote my own function:
/** * Returns a human readable presentation of an object, its properties and its values. * @param obj The object * @param attr You can use this parameter in order to specify a prefix for each property * @return Returns a string * * @author ComFreek * @license Public Domain */ function logObject(obj, attr) { var str = ""; attr = attr || ""; for (var attrname in obj) { if (typeof obj[attrname] == "object") { str += "\n" + logObject(obj[attrname], attr + "." + attrname) + "\n"; } else { str += attr + "." + attrname + "=" + obj[attrname] + "\n"; } } return str; }Some sample inputs and outputs:
var obj = { "foo": "bar", "bar": "foo", "fooObj": { "barProp": "fooVal", "fooProp": "barVal", "barUnderObj": { "test": "test" } } }; console.log(logObject(obj));This outputs:
.foo=bar .bar=foo .fooObj.barProp=fooVal .fooObj.fooProp=barVal .fooObj.barUnderObj.test=testThe same code but with second argument given:
console.log( logObject(obj, "fooObj") );Output:
fooObj.foo=bar fooObj.bar=foo fooObj.fooObj.barProp=fooVal fooObj.fooObj.fooProp=barVal fooObj.fooObj.barUnderObj.test=test
No comments:
Post a Comment