You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过递归函数生成含JSON路径的对象以简化useTranslation调用?

实现递归生成i18n键值映射对象

你可以通过递归遍历翻译JSON的每一层,逐步拼接键路径,最终生成目标结构的对象。核心逻辑如下:

  • 遍历当前对象的每个键值对
  • 若值为对象,递归处理该子对象并拼接父路径
  • 若值为字符串,生成包含完整键路径和对应值的对象

具体实现代码

function generateI18nKeys(translations, parentKey = '') {
  return Object.fromEntries(
    Object.entries(translations).map(([key, value]) => {
      const fullKey = parentKey ? `${parentKey}.${key}` : key;
      if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
        // 递归处理子对象
        return [key, generateI18nKeys(value, fullKey)];
      } else {
        // 生成包含key和value的目标对象
        return [key, { key: fullKey, value }];
      }
    })
  );
}

// 示例调用
const translations = {
    "userInfo":{
        "name": "Name",
        "lastname": "Last Name"
    },
    "sideMenu":{
        "home":"Home"
    }
};

const i18nKeys = generateI18nKeys(translations);

代码说明

  • generateI18nKeys 接受两个参数:translations(原始翻译JSON)和 parentKey(当前层级的父路径,默认空字符串)
  • 用 Object.entries 遍历键值对,再通过 Object.fromEntries 将处理后的键值对重新组合为对象
  • 遇到嵌套对象时递归调用自身,拼接完整路径;遇到字符串值时直接生成目标结构

使用方式

之后你可以这样调用翻译函数:

// 假设t是useTranslation返回的翻译函数
t(i18nKeys.userInfo.name.key, i18nKeys.userInfo.name.value);

内容的提问来源于stack exchange,提问作者ivanpetrijevci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 18:15:41