简体   繁体   中英

Change snake_case to camelCase

Currently, the scenario is that the data coming from the Nodejs backend is in snake_case but the frontend is using camelCase. I am using snakeize and camelize to convert casing but with a compromise.

Problem

ObjectId _id using camelize is converted to Id while I am expecting as id .

Expectation .

_id must to converted to id

I think the problem is that the package you're using removes every underscore he finds and converts the letter after it to upper case.
You just need to check if the first letter is underscore and remove it:

const obj = { "_id" : 12345678, "name" : "John Doe" };
for (let key in obj){
    if (key[0] === "_"){
        const newKey = key.slice(1);
        obj[newKey] = obj[key];
        delete obj[key];
    }
}

console.log(obj)

Recursive:递归:

const obj = { "_id" : 12345678, "name" : "John Doe", "inner_obj" : { "_id" : 12345678 } };

function removeUnderscore(obj){
    for (let key in obj){
        let newKey = key;
        if (key[0] === "_"){
            newKey = key.slice(1);
            obj[newKey] = obj[key];
            delete obj[key];
        }
        if (typeof obj[newKey] === "object" && !Array.isArray(obj[newKey])) removeUnderscore(obj[newKey])
    }
}

removeUnderscore(obj);

console.log(obj);

It would be hard to discern your architecture or data flow from the statement above.

But I would say your current approach of reformatting the entire data structure to either be snake or camel as unnecessary. unless this data structure is being passed through functions and you have no control how it's retreated.

Reformatting the data structure requires a recursive loop. your time and complexity will increase as the data structure grows in size and nesting.

I would suggest that you create a function that wraps lo-dash.get and change-case.

Exmaple: getData(dataStructure, path, case, defaultValue);

Formatting an entire data structure up front can be costly and cause performance issues

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM