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

如何用JavaScript根据name值查找JSON对象的路径?

根据角色名称查找JSON对象路径(JavaScript实现)

问题背景

已知char_table.json的结构如下:

{
  "char_285_medic2": {
    "name": "Lancet-2",
    "description": "Restores the HP of allies and ignores the Deployment Limit, but has a long Redeployment Time",
    "canUseGeneralPotentialItem": false,
    "canUseActivityPotentialItem": false
  },
  "char_291_aglina": {
    "name": "Angelina",
    "description": "Deals Arts damage and Slows the target for a short time",
    "canUseGeneralPotentialItem": true,
    "canUseActivityPotentialItem": false
  },
  "char_2013_cerber": {
    "name": "Ceobe",
    "description": "Deals Arts damage",
    "canUseGeneralPotentialItem": true,
    "canUseActivityPotentialItem": false
  },
  ...
}

现在仅持有角色的name变量,需要找到对应对象的完整路径(例如输入"Angelina"返回char_table.char_291_aglina),如何用JavaScript实现?


解决方案

核心思路

  1. 将JSON文件解析为JavaScript对象
  2. 遍历对象的所有键,精确匹配每个对象的name属性
  3. 匹配成功后拼接成要求的路径格式

代码实现

核心查找函数

这个函数负责接收解析后的JSON对象和目标名称,返回对应路径:

function findCharPath(charTable, targetName) {
  // 遍历charTable的所有键
  for (const key of Object.keys(charTable)) {
    // 精确匹配name值
    if (charTable[key].name === targetName) {
      return `char_table.${key}`;
    }
  }
  // 未找到时返回null
  return null;
}

Node.js环境完整示例

如果是在Node.js环境中读取本地JSON文件:

const fs = require('fs');

// 读取并解析JSON文件
fs.readFile('./char_table.json', 'utf8', (err, data) => {
  if (err) {
    console.error('读取文件失败:', err);
    return;
  }
  try {
    const charTable = JSON.parse(data);
    const targetName = 'Angelina'; // 替换为你要查找的角色名称
    const resultPath = findCharPath(charTable, targetName);
    
    if (resultPath) {
      console.log('匹配路径:', resultPath);
    } else {
      console.log('未找到对应角色');
    }
  } catch (parseErr) {
    console.error('解析JSON失败:', parseErr);
  }
});

// 核心查找函数
function findCharPath(charTable, targetName) {
  for (const key of Object.keys(charTable)) {
    if (charTable[key].name === targetName) {
      return `char_table.${key}`;
    }
  }
  return null;
}

浏览器环境完整示例

如果是在浏览器中通过网络请求获取JSON文件:

async function getCharacterPath(targetName) {
  try {
    const response = await fetch('./char_table.json');
    const charTable = await response.json();
    
    for (const key of Object.keys(charTable)) {
      if (charTable[key].name === targetName) {
        return `char_table.${key}`;
      }
    }
    return null;
  } catch (err) {
    console.error('获取数据失败:', err);
    return null;
  }
}

// 使用示例
getCharacterPath('Ceobe').then(path => {
  if (path) {
    console.log('匹配路径:', path);
  } else {
    console.log('未找到对应角色');
  }
});

注意事项

  • 匹配为精确匹配,区分大小写(例如"angelina"和"Angelina"会被视为不同值)
  • 若存在多个角色name相同的情况,函数会返回第一个匹配到的路径
  • 未找到对应角色时,函数返回null,可根据需求修改为自定义提示内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:37:50