JoeZhao

跨出界

Hey, I’m JoeZhao, a software engineer, and a gamer.

change json underline to camp

This is a interview question I encountered, so I'm recording it.

The question is: How to change all the keys of a JSON data from underscore to camel case?

Below is the implementation method during the answer process:

const testData = {
    a_bbb: 123,
    a_g: [1, 2, 3, 4],
    a_d: {
        s: 2,
        s_d: 3
    },
    a_f: [1, 2, 3, {
        a_g: 5
    }],
    a_d_s: 1
}

/**
 * Convert _w to W
 */
function toCame(str) {
    return str.replace(/\_(\w)/g, function(a, b) {
        return b.toUpperCase();
    });
}

/**
 * Change all the keys of a JSON data from underscore to camel case
 * 
 * @param {object | array} value The object or array to be processed
 * @returns {object | array} The processed object or array
 */
function mapKeysToCamelCase(data) {
    if(data instanceof Array) {
        data.forEach(function(v, index) {
            mapKeysToCamelCase(v);
        });
    } else if(data instanceof Object) {
        Object.keys(data).forEach(function(v, index) {
            var newValue = toCame(v);
            console.info(newValue);
            
            // If the names are the same, it means there may be no conversion
            if(newValue != v) {
                data[newValue] = data[v];
                delete data[v];
            }

            // Recursion
            mapKeysToCamelCase(data[newValue]);
        });
    }

    return data;
}

console.log(mapKeysToCamelCase(testData))

Further thinking:

  1. This is directly operating on the original object, how to copy a new object?
  2. ES should have a better method for looping through objects, how to use the new features?

...To be continued

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.