[Solved] How do I write a recursive function in Javascript to add up all of the string values of a deeply nested object?


Here’s a very simple implementation that should work for simple objects like this:

var walkProps = function(obj) {
    var s = "";
    for(var x in obj)
    {
        if(typeof obj[x] === "string")
            s += obj[x];
        else
            s += walkProps(obj[x]);
    }
    return s;
}

Demonstration

Note, though, that that depends on the order in which for-in visits the properties on the object, which is not specified and can vary by engine and by how the object is constructed (for instance, the order in which the properties were added).


Update: With some slight modification, this can be used to return the values based on the alphabetical order of the keys. This method is not sensitive to implementation-dependent ordering of properties:

var walkProps = function(obj) {
    var s = "", i = 0, keys = Object.keys(obj).sort(), i;
    for(; i < keys.length; i++)
    {
        if(typeof obj[keys[i]] === "string")
            s += obj[keys[i]];
        else
            s += walkProps(obj[keys[i]]);
    }
    return s;
}

So even if "prop3" comes before "prop2" it will still return the same output.

Demonstration

3

solved How do I write a recursive function in Javascript to add up all of the string values of a deeply nested object?