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

如何在JavaScript中搜索对比对象数组的值并按输入返回对应结果

enter image description here
enter image description here

实现方案

思路

  1. 预先将分类数据集转为ID到分类对象的映射表,避免每次查找父分类遍历全数组,提升查找效率
  2. 查找目标分类后,直接通过映射表快速获取对应的父分类信息,和当前分类信息整合输出即可

完整代码

const dataSet = [{
    categoryId: 100,
    parentCategoryId: -1,
    name: "Business",
    keyword: "Money",
  },
  {
    categoryId: 200,
    parentCategoryId: -1,
    name: "Tutoring",
    keyword: "Teaching",
  },
  {
    categoryId: 101,
    parentCategoryId: 100,
    name: "Accounting",
    keyword: "Taxes",
  },
  {
    categoryId: 102,
    parentCategoryId: 100,
    name: "Taxation",
    keyword: "",
  },
  {
    categoryId: 201,
    parentCategoryId: 200,
    name: "Computer",
    keyword: "",
  },
  {
    categoryId: 103,
    parentCategoryId: 101,
    name: "Corporate Tax",
    keyword: "",
  },
  {
    categoryId: 202,
    parentCategoryId: 201,
    name: "Operating System",
    keyword: "",
  },
  {
    categoryId: 109,
    parentCategoryId: 101,
    name: "Small Business Tax",
    keyword: "",
  }
]

// 构建ID到分类对象的映射,仅初始化一次
const categoryMap = dataSet.reduce((map, item) => {
  map[item.categoryId] = item
  return map
}, {})

function solution(X) {
  const targetCategory = categoryMap[X]
  if (!targetCategory) {
    console.log('未找到匹配的分类')
    return
  }
  // 查找父分类
  const parentCategory = categoryMap[targetCategory.parentCategoryId]
  
  // 拼接输出内容
  let output = `当前分类信息:
  分类ID:${targetCategory.categoryId}
  分类名称:${targetCategory.name}
  关键词:${targetCategory.keyword || '无'}`

  if (parentCategory) {
    output += `
关联父分类信息:
  父分类ID:${parentCategory.categoryId}
  父分类名称:${parentCategory.name}
  父分类关键词:${parentCategory.keyword || '无'}`
  }

  console.log(output)
}

// 测试
solution(201)

运行效果

调用solution(201)后输出如下:

当前分类信息:
  分类ID:201
  分类名称:Computer
  关键词:无
关联父分类信息:
  父分类ID:200
  父分类名称:Tutoring
  父分类关键词:Teaching

如果需要获取完整的多级父分类链路,可以使用循环遍历的方式实现:

function getFullCategoryChain(categoryId) {
  const chain = []
  let current = categoryMap[categoryId]
  while (current) {
    chain.unshift(current)
    current = categoryMap[current.parentCategoryId]
  }
  return chain
}

// 示例:获取ID为103的分类全链路
console.log(getFullCategoryChain(103))
// 输出顺序为 一级分类Business → 二级分类Accounting → 三级分类Corporate Tax

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:45:04