Skip to content Skip to sidebar Skip to footer

Prepending Namespace To All Of A Json Object's Keys

I'm not overly knowledgeable in JavaScript, but here's the rundown on what I'm trying to do. I have a JSON object that is prepared by an external source. I'm using that Object as-

Solution 1:

Try to check the code to see if I missed any unhandled cases. You have to check for a few things before you use it I guess...

var obj1 = {
  "key1": "value",
  "key2": "value",
  "key3": "value",
  "key4": {
   "subkey1": "value",
   "subkey2": "value"
  }
};

var rename = function(obj, prefix){

    if(typeof obj !== 'object' || !obj){
        return false;    // check the obj argument somehow
    }

    var keys = Object.keys(obj),
        keysLen = keys.length,
        prefix = prefix || '';

    for(var i=0; i<keysLen ;i++){

        obj[prefix+keys[i]] = obj[keys[i]];
        if(typeof obj[keys[i]]=== 'object'){
            rename(obj[prefix+keys[i]],prefix);
        }
        delete obj[keys[i]];
    }

    return obj;
};

Post a Comment for "Prepending Namespace To All Of A Json Object's Keys"