[英]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.目前,场景是来自 Nodejs 后端的数据采用 snake_case,但前端使用的是驼峰命名法。 I am using snakeize and camelize to convert casing but with a compromise.
我正在使用snakeize和camelize来转换套管,但有妥协。
Problem问题
ObjectId _id
using camelize is converted to Id
while I am expecting as id
.使用 camelize 的 ObjectId
_id
被转换为Id
而我期望为id
。
Expectation .期待。
_id
must to converted to id
_id
必须转换为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.我认为问题在于您使用的 package 删除了他找到的每个下划线并将其后的字母转换为大写。
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);
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.我建议您创建一个包装 lo-dash.get 和 change-case 的 function。
Exmaple: getData(dataStructure, path, case, defaultValue);
示例:
getData(dataStructure, path, case, defaultValue);
Formatting an entire data structure up front can be costly and cause performance issues预先格式化整个数据结构可能代价高昂并且会导致性能问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.