snake_case转camelCase问题:_id经camelize转换未得到预期id
解决camelize转换后_id变为Id的问题
camelize的默认规则会把下划线后的首字母大写,所以_id会被转成Id,要实现转成id的需求,有几种简单的处理方式:
方式一:转换后手动修正字段
先使用camelize处理整个对象/数组,再单独把生成的Id字段重命名为id,适用于结构简单的数据:
const camelize = require('camelize'); function transformData(data) { const camelized = camelize(data); // 处理单个对象 if (typeof camelized === 'object' && camelized !== null && !Array.isArray(camelized)) { if ('Id' in camelized) { camelized.id = camelized.Id; delete camelized.Id; } } // 处理数组 else if (Array.isArray(camelized)) { camelized.forEach(item => { if ('Id' in item) { item.id = item.Id; delete item.Id; } }); } return camelized; }
方式二:自定义转换逻辑(递归处理)
如果数据结构嵌套较深,递归遍历所有字段,单独处理_id,其他字段用camelCase规则转换:
// 可以自己实现简单的camelCase转换,也可以用change-case库 function simpleCamelCase(str) { return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()); } function customTransform(obj) { // 处理数组 if (Array.isArray(obj)) { return obj.map(customTransform); } // 处理对象 if (typeof obj === 'object' && obj !== null) { const result = {}; Object.entries(obj).forEach(([key, value]) => { const newKey = key === '_id' ? 'id' : simpleCamelCase(key); result[newKey] = customTransform(value); }); return result; } // 基础类型直接返回 return obj; }
方式三:临时替换字段规避默认规则
先把所有_id替换成临时字段,用camelize处理后再改回id:
const camelize = require('camelize'); function transformWithTempField(data) { // 递归替换_id为临时标识 function replaceTempId(item) { if (Array.isArray(item)) return item.map(replaceTempId); if (typeof item !== 'object' || item === null) return item; const newItem = {...item}; if ('_id' in newItem) { newItem.__temp_id = newItem._id; delete newItem._id; } Object.keys(newItem).forEach(k => newItem[k] = replaceTempId(newItem[k])); return newItem; } const tempData = replaceTempId(data); const camelized = camelize(tempData); // 把转换后的__tempId改回id function restoreId(item) { if (Array.isArray(item)) return item.map(restoreId); if (typeof item !== 'object' || item === null) return item; const newItem = {...item}; if ('__tempId' in newItem) { newItem.id = newItem.__tempId; delete newItem.__tempId; } Object.keys(newItem).forEach(k => newItem[k] = restoreId(newItem[k])); return newItem; } return restoreId(camelized); }
内容的提问来源于stack exchange,提问作者power-cut
相关产品推荐
相关产品推荐

