John Livermore
John Livermore

Reputation: 31343

js object passed to a function becomes a string

`I have written a js function to traverse a javascript object and output it's contents with console.log(). It recursively calls itself when a property that is an object is encountered. The problem is in the recursive loops, the passed in property doesn't show any child properties.

Take the sample below (also at JS Fiddle), once the jsObject.payload is passed into the recursive call, 'payload' appears to revert to a simple string object.

var EnumerateObject = function(object, path) {
    if (!path) path = '';

    for (var property in object) {
        if (object.hasOwnProperty(property)) {
            if (typeof object[property] === "object") EnumerateObject(property, path + '.' + property);
            else console.log(path + '.' + property + '=' + typeof property);
        }
    }
}

var json = '{"success": true, "error": "", "payload": { "fetch": "1", "xml": "<xml />" }}';
var jsObject = $.parseJSON(json);

EnumerateObject(jsObject);

I know I am missing something subtle here, but I am not sure why my passed in 'property' to the 'object' parameter suddenly becomes a string?

Upvotes: 1

Views: 1066

Answers (3)

Baz1nga
Baz1nga

Reputation: 15579

here is the fixed solution:

var EnumerateObject = function(jsonObject, path) {
    if (!path) path = '';

    for (var prop in jsonObject) {
        if (jsonObject.hasOwnProperty(prop )) {

            if (typeof(jsonObject[prop ]) === "object") EnumerateObject(jsonObject[prop ], path + '.' + prop );
            else console.log(path + '.' + prop + '=' + typeof prop );
        }
    }
}

var json = '{"success": true, "error": "", "payload": { "fetch": "1", "xml": "<xml />" }}';
var jsObject = $.parseJSON(json);

console.log(typeof(jsObject["payload"]));
EnumerateObject(jsObject);

please remove the use of reserverd keywords like object.. IE might crap out..

Upvotes: 1

Alex Wayne
Alex Wayne

Reputation: 187282

Object keys are always strings. So when you do typeof property then property is the key not the value. You probably mean to do typeof object[property].

So they are NOT being converted to strings, you were just getting the type of the wrong object.

Upvotes: 2

Jimmy
Jimmy

Reputation: 91502

property is a string containing the value "payload".

object[property] is {'fetch':'1', 'xml':.... }

Upvotes: 3

Related Questions