user3491721
user3491721

Reputation: 3

Recursively manipulate javascript object data ends

Is there a way to walk through an arbitrary Javascript object, and alter it at its data ends, wherever its not another nested object?

So given the below, could I log an object where '123', 'bar', 'die', 'or' become 'xyz'?

var jso = {
    hello:[
        { foo:'bar' },
        { abc: { def:'123' } }
    ],
    world:[
        { ride:['or','die'] }
    ]
};

function recurse(object) {
    if (Object.prototype.toString.call(object) === '[object Array]') {
        var l = object.length;
        while(l--){ 
            recurse(object[l]) 
        }
    } else if(typeof object === 'object') {
        for(var key in object) {
            recurse(object[key])
        }
    } else {
        object = 'xyz';
    }
}

recurse(jso)
console.log(jso)

Upvotes: 0

Views: 118

Answers (3)

Scott Sauyet
Scott Sauyet

Reputation: 50797

Nice and simple:

function recurse(object) {
    Object.keys(object).forEach(function(key) {
        if (typeof object[key] == "object") {
            recurse(object[key]);
        } else {
            object[key] = "xyz";
        }
    });
}

Upvotes: 0

Bergi
Bergi

Reputation: 664579

object = 'xyz';

That won't work, as it just changes the object variable that is local to the function call. To actually modify an object, you need to assign to a property:

function recurse(object) {
    if(Object.prototype.toString.call(object) === '[object Array]'){
        for (var l = object.length; l--; ) { 
            if (typeof object[l] == 'object')
                recurse(object[l]);
            else
                object[l] = 'xyz';
        }
    } else {
        for(var key in object) {
            if (typeof object[key] == 'object')
                recurse(object[key]);
            else
                object[key] = 'xyz';
        }
    }
}

or (better)

function recurse(object) {
    if (typeof object !== 'object')
        return 'xyz';

    if (Object.prototype.toString.call(object) === '[object Array]'){
        for (var l = object.length; l--; ) { 
            object[l] = recurse(object[l]);
        }
    } else {
        for (var key in object) {
            object[key] = recurse(object[key])
        }
    }
    return object;
}

Upvotes: 3

SomeKittens
SomeKittens

Reputation: 39532

Object.keys is nice in these situations.

function recurse(datum) {
    if (Array.isArray(datum)) {
        datum.forEach(function (arrayItem, idx) {
            datum[idx] = recurse(datum[idx]);
        });
        return datum;
    } else if (typeof datum === 'object') {
        Object.keys(datum).forEach(function (key) {
            datum[key] = recurse(datum[key]);
        });
        return datum;
    } else {
        return 'xyz';
    }
}

JSFiddle

Upvotes: 0

Related Questions