2

How do I read a Javascript Object when I don't know what's in it?

I've been working on node.js and have a variable for which I really don't know what's in it. When I try sys.puts:

sys.puts(headers) // returns [object Object]

If there was something like a print_r in javascript, that would have been fine.

1
  • You may try to convert it to a JSON string... Commented Dec 10, 2010 at 13:30

4 Answers 4

4

You can loop over its properties with

for (var item in headers)
{
  // item is the name of the property
  // headers[item] is the value
}

example at http://www.jsfiddle.net/gaby/CVJry/3/ (requires console)

If you want to limit the results to direct properties (not inherited through the prototype chain) then use as well the hasOwnProperty method.

example at http://www.jsfiddle.net/gaby/CVJry/2/

Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't the item variable be declared somewhere?
@Šime, it should .. added :)
2

Most web browsers can use the JSON-object to print the contents of an object,

writeln(JSON.stringify(your_object));

If that fails, you can create your own stringifier;

var stringify = function(current) {
    if (typeof current != 'object')
        return current;

    var contents = '{';
    for (property in current) {
        contents += property + ": " + stringify(current[property]) + ", ";
    }

    return contents.substring(0, contents.length - 2) + "}";
}

var my_object = {my_string: 'One', another_object: {extra: 'Two'}};
writeln(stringify(my_object));

Comments

1

You can loop through your object to know its properties & their values

Suppose your object is

var emp = {
           name:'abc', 
           age:12, 
           designation:'A'
        }

Now you can read its details in JS

for(property in emp ){
 alert(emp[property] + " " +property);
}

If you have firebug in added in your Firefox browser, open it & write either in JS or JS window in Firebug console.

console.log(a);

Comments

0

If you need it just to check what's in an object (ie, it's relevant to you for some reason, but you don't need that functionality in your script), you can just use Firebug to get the object and check exactly what's in it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.