Andy  Gee Andy Gee - 5 months ago 15
jQuery Question

Renaming object keys recursively

I have a recursive function to rename the key names of an object but I'm unable to figure out how to rename 2 of the keys (problem keys are objects)

I think the problem is where I'm checking for object type but how can I rename the key at that point?

The actual arrays are very large but a cut down version is below.

Any help appreciated.

var keys_short = ['ch','d','u','tz'];
var keys_long = ['children','data','user_id','time_zone'];
function refit_keys(o){
build = {};
for (var i in o){
if(typeof(o[i])=="object"){
o[i] = refit_keys(o[i]);
build = o;
}else{
var ix = keys_short.indexOf(i);
if(ix!=-1){
build[keys_long[ix]] = o[keys_short[ix]];
}
}
}
return build;
}


My input looks like this:

{
"id":"1",
"ch":[
{
"id":"3",
"ch":[
],
"d":{
"u":"3",
"tz":"8.00"
}
},
{
"id":"45",
"ch":[
{
"id":"70",
"ch":[
{
"id":"43",
"ch":[
],
"d":{
"u":"43",
"tz":"-7.00"
}
}
],
"d":{
"u":"70",
"tz":"-7.00"
}
}
],
"d":{
"u":"45",
"tz":"-7.00"
}
}
],
"d":{
"u":"1",
"tz":"8.00"
}
}


My output like this:

{
"id":"1",
"ch":[
{
"id":"3",
"ch":[
],
"d":{
"user_id":"3",
"time_zone":"8.00"
}
},
{
"id":"45",
"ch":[
{
"id":"70",
"ch":[
{
"id":"43",
"ch":[
],
"d":{
"user_id":"43",
"time_zone":"-7.00"
}
}
],
"d":{
"user_id":"70",
"time_zone":"-7.00"
}
}
],
"d":{
"user_id":"45",
"time_zone":"-7.00"
}
}
],
"d":{
"user_id":"1",
"time_zone":"8.00"
}
}

Answer

There are a couple of problems there.

One is that you're falling prey to The Horror of Implicit Globals by failing to declare your build variable in the function.

But the logic has issues as well, here's a minimal reworking:

var keys_short = ['ch','d','u','tz'];
var keys_long = ['children','data','user_id','time_zone'];
function refit_keys(o){
    var build, key, destKey, ix, value;

    build = {};
    for (key in o) {
        // Get the destination key
        ix = keys_short.indexOf(key);
        destKey = ix === -1 ? key : keys_long[ix];

        // Get the value
        value = o[key];

        // If this is an object, recurse
        if (typeof value === "object") {
            value = refit_keys(value);
        }

        // Set it on the result using the destination key
        build[destKey] = value;
    }
    return build;
}

Live Example | Source

But rather than parallel arrays, I'd suggest using a key map:

var mapShortToLong = {
    "ch": "children",
    "d":  "data",
    "u":  "user_id",
    "tz": "time_zone"
};
function refit_keys(o){
    var build, key, destKey, ix, value;

    build = {};
    for (key in o) {
        // Get the destination key
        destKey = mapShortToLong[key] || key;

        // Get the value
        value = o[key];

        // If this is an object, recurse
        if (typeof value === "object") {
            value = refit_keys(value);
        }

        // Set it on the result using the destination key
        build[destKey] = value;
    }
    return build;
}

Live Example | Source