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

React/Typescript中如何查找值对应的数组类型键并修改关联对象

实现方案

原生 TypeScript 实现

直接遍历checkAgainst的键,逐个判断数组是否包含目标值,匹配后修改output对应属性即可,额外做了类型兼容处理避免TS类型报错:

const output = {
    a: false,
    b: false,
    c: false,
}

const checkAgainst = {
    a: ["1", "2", "3"],
    b: ["4", "5", "6"],
    c: ["7", "8", "9"]
}

const checkThing = "5"

// 核心逻辑
for (const key of Object.keys(checkAgainst) as Array<keyof typeof checkAgainst>) {
  if (checkAgainst[key].includes(checkThing)) {
    output[key] = true
    // 若只需匹配第一个命中的键,取消下方注释中断循环即可
    // break
  }
}

return output;

Lodash 简化实现

项目已引入lodash的话,可以直接用_.findKey方法快速查找匹配的键,代码更简洁:

import { findKey } from 'lodash'

// ... 其余变量声明同上

const matchedKey = findKey(checkAgainst, arr => arr.includes(checkThing))
// 校验匹配到的键是否存在于output中,避免非法属性赋值
if (matchedKey && Object.prototype.hasOwnProperty.call(output, matchedKey)) {
  output[matchedKey as keyof typeof output] = true
}

return output

注意事项

  • 如果同一个目标值可能出现在多个checkAgainst的数组中,原生方案去掉break即可将所有命中的output属性设为true
  • 如果你项目中output和checkAgainst的键是严格一一对应的,可以省略键存在性校验逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:15:01