在JavaScript中,多维数组通常是指包含嵌套对象或数组的数据结构。更改这些嵌套结构的键名称是一个常见的数据转换需求。
function renameKeys(obj, keyMap) {
if (Array.isArray(obj)) {
return obj.map(item => renameKeys(item, keyMap));
} else if (typeof obj === 'object' && obj !== null) {
const newObj = {};
for (const key in obj) {
const newKey = keyMap[key] || key;
newObj[newKey] = renameKeys(obj[key], keyMap);
}
return newObj;
}
return obj;
}
// 使用示例
const originalData = {
id: 1,
user_info: {
first_name: 'John',
last_name: 'Doe',
contacts: [
{ phone_type: 'mobile', phone_number: '123-456-7890' }
]
}
};
const keyMapping = {
first_name: 'firstName',
last_name: 'lastName',
phone_type: 'type',
phone_number: 'number'
};
const transformedData = renameKeys(originalData, keyMapping);
console.log(transformedData);
function renameKeysWithJQuery(obj, keyMap) {
const newObj = {};
$.each(obj, function(key, value) {
const newKey = keyMap[key] || key;
if ($.isPlainObject(value)) {
newObj[newKey] = renameKeysWithJQuery(value, keyMap);
} else if ($.isArray(value)) {
newObj[newKey] = value.map(item =>
$.isPlainObject(item) ? renameKeysWithJQuery(item, keyMap) : item
);
} else {
newObj[newKey] = value;
}
});
return newObj;
}
// 使用示例同上
const renameKeysES6 = (obj, keyMap) => {
if (Array.isArray(obj)) return obj.map(item => renameKeysES6(item, keyMap));
if (typeof obj !== 'object' || obj === null) return obj;
return Object.entries(obj).reduce((acc, [key, value]) => {
const newKey = keyMap[key] || key;
acc[newKey] = renameKeysES6(value, keyMap);
return acc;
}, {});
};
_.mapKeys
(但需要处理嵌套)问题1:转换后某些字段丢失了
问题2:性能问题处理大数据量
// 分块处理大数据示例
function processLargeDataInChunks(data, keyMap, chunkSize = 1000) {
const result = [];
for (let i = 0; i < data.length; i += chunkSize) {
const chunk = data.slice(i, i + chunkSize);
result.push(...chunk.map(item => renameKeys(item, keyMap)));
}
return result;
}