skip to Main Content

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

2

Answers


  1. 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)
    

    Edit:
    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);
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search