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

如何使用JS在JSON payload中查找指定locale对应的direction属性值

实现代码

你可以直接用JS数组的find()方法完成匹配,示例实现如下:

// 入参说明:
// apiResponse:API返回的已解析JS对象(如果拿到的是JSON字符串,先调用JSON.parse()转成对象)
// targetLocale:你要匹配的目标locale值,比如传入'en_US'
function getMatchedLangDirection(apiResponse, targetLocale) {
  // 从locales数组中匹配对应locale的项
  const matchedItem = apiResponse.data.study.locales.find(
    item => item.locale === targetLocale
  )
  // 无匹配时的容错处理
  if (!matchedItem) return null
  // 返回对应direction属性
  return matchedItem.language.direction
}

// 调用测试
const testLocale = 'en_US'
const result = getMatchedLangDirection(你的API返回结果变量, testLocale)
console.log(result) // 输出 ltr

说明

  • Array.find()会遍历数组返回第一个符合匹配条件的元素,找不到则返回undefined,加容错判断是为了避免匹配失败时报属性访问错误
  • 如果你需要获取整个匹配项的完整结构,直接返回matchedItem即可,里面就包含{"direction": "ltr"}的完整结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:36:01