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

如何修改嵌套JSON对象内所有指定属性的取值,适配当前locale参数

递归遍历替换嵌套多语言属性解决方案

实现思路

通过深度优先递归遍历所有嵌套的数组、对象结构,自动识别多语言格式的字段并替换为对应locale的取值,无需手动适配嵌套层级。

完整实现代码

首先定义多语言标识:

const locale = "en"

通用递归处理函数(自动识别所有多语言结构):

function processI18n(data, targetLocale) {
  // 处理数组:递归遍历每一项
  if (Array.isArray(data)) {
    return data.map(item => processI18n(item, targetLocale))
  }
  // 处理对象
  if (data && typeof data === 'object') {
    // 当前对象本身就是多语言结构(包含目标locale字段),直接返回对应取值
    if (Object.prototype.hasOwnProperty.call(data, targetLocale)) {
      return data[targetLocale]
    }
    // 遍历对象所有属性递归处理
    const processedObj = {}
    for (const key in data) {
      if (Object.prototype.hasOwnProperty.call(data, key)) {
        processedObj[key] = processI18n(data[key], targetLocale)
      }
    }
    return processedObj
  }
  // 基础数据类型直接返回
  return data
}

使用方法

直接传入原始JSON数据和目标locale即可得到处理后的结果:

const processedResult = processI18n(result, locale)

安全优化版本(仅处理指定属性)

如果担心其他业务字段碰巧包含en/fi等键被误修改,可以限制仅处理指定的多语言属性名:

// 第三个参数指定需要处理的多语言属性名列表
function processI18n(data, targetLocale, i18nKeys = ['navTitle', 'data']) {
  if (Array.isArray(data)) {
    return data.map(item => processI18n(item, targetLocale, i18nKeys))
  }
  if (data && typeof data === 'object') {
    const processedObj = {}
    for (const key in data) {
      if (Object.prototype.hasOwnProperty.call(data, key)) {
        const val = data[key]
        // 仅属性名在指定列表中且为多语言结构时才替换
        if (i18nKeys.includes(key) && val && typeof val === 'object' && Object.prototype.hasOwnProperty.call(val, targetLocale)) {
          processedObj[key] = val[targetLocale]
        } else {
          processedObj[key] = processI18n(val, targetLocale, i18nKeys)
        }
      }
    }
    return processedObj
  }
  return data
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:36:07