Konstantinos-infogeek
4/26/2015 - 9:05 PM

A simple, fast and safe way to loop map an object

A simple, fast and safe way to loop map an object

var person = {
    'firstname' : 'Babar',
    'lastname' : 'Elephantsking',
    'age' : '30',
    'attrs' : {'height' : '300' , 'weight' : '3000' }
};


function mapObject(obj) {
    var objKeys = Object.keys(obj); //This returns an array of person properties

    var index = 0;
    for (; index < objKeys.length; index = index + 1) {
        var propertyName = objKeys[index];

        //set new value for property using a closure
        obj[propertyName] = (function (property) {

            return (function (prop) {
                if (typeof prop === "object") {
                    return mapObject(prop);
                }
                return prop+'lalal';
            })(property);

        })(obj[propertyName]);
    }
    return obj;
}

var b = mapObject(person);
var person = {
    'firstname' : 'Babar',
    'lastname' : 'Elephantsking',
    'age' : '30'
};

var objKeys = Object.keys(person); //This returns an array of person properties

var index = 0;
for(;index < objKeys.length; index = index + 1){
    var propertyName = objKeys[index];
    
    //set new value for property using a closure
    person[propertyName] = (function(property){
        if(!isNaN(property)){
            return parseInt(property) + 2;
        }
        return property;
        
    })(person[propertyName]);
}