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

如何在对象数组中使用逻辑或实现多名称匹配?

问题:无重音输入匹配带重音的宝可梦条目

我希望让用户无需输入重音即可匹配到对应宝可梦条目,目前尝试在name属性中使用"Flabébé" || "Flabebe"的写法但未生效,不想重复数组条目,询问是否可在数组中使用逻辑或运算符实现该需求?

用户提供的代码片段:

let pokeArray = {
  pokemon: [
    {
      name: "Flabébé"  || "Flabebe",
      type: ["fairy"],
      imageData: "Not In Use",
      anchor: "Not In Use",
    },
]}


const pokeName = pokeArray.pokemon.map((x)=>x.name.toLowerCase())
let myPokemon = "Flabebe"
let inputMyPokemon = pokeName.indexOf(myPokemon.toLowerCase())

为什么逻辑或写法不生效

"Flabébé" || "Flabebe"这种写法在JS里只会返回第一个真值,也就是"Flabébé",第二个字符串根本不会被赋值给name属性。所以你的pokeName数组里只会有"flabébé",自然匹配不到无重音的"flabebe"。

不用重复数组条目的解决方案

方案1:将name设为包含所有变体的数组

把每个宝可梦的name改成数组,包含带重音和不带重音的版本,匹配时检查输入是否在数组的小写版本里:

let pokeArray = {
  pokemon: [
    {
      name: ["Flabébé", "Flabebe"],
      type: ["fairy"],
      imageData: "Not In Use",
      anchor: "Not In Use",
    },
]}

// 调整匹配逻辑
const matchedPokemon = pokeArray.pokemon.find(poke => 
  poke.name.some(name => name.toLowerCase() === myPokemon.toLowerCase())
);
// matchedPokemon即为匹配到的条目(未找到则为undefined)

方案2:添加专门的搜索用字段(推荐)

给每个宝可梦添加一个searchName字段,存储去掉重音的标准化版本,匹配时用这个字段对比:

// 工具函数:移除字符串中的重音符号
function removeAccents(str) {
  return str.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
}

let pokeArray = {
  pokemon: [
    {
      name: "Flabébé",
      searchName: removeAccents("Flabébé"), // 结果为"Flabebe"
      type: ["fairy"],
      imageData: "Not In Use",
      anchor: "Not In Use",
    },
]}

// 匹配时同步处理输入
const inputClean = removeAccents(myPokemon.toLowerCase());
const matchedIndex = pokeArray.pokemon.findIndex(poke => 
  poke.searchName.toLowerCase() === inputClean
);

方案3:匹配时动态去重音(无需修改原数据)

如果不想改动原数据结构,可以在匹配时同时把原名字和输入都转换成无重音版本:

function removeAccents(str) {
  return str.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
}

let myPokemon = "Flabebe";
const inputClean = removeAccents(myPokemon.toLowerCase());

const matchedIndex = pokeArray.pokemon.findIndex(poke => 
  removeAccents(poke.name.toLowerCase()) === inputClean
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 12:45:40