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

无法从数组中动态查找对象,如何根据client_id匹配oauthClients数组的值

问题修复方案

原有代码的核心问题

  • 你的oauthClients数组中每个对象的键名本身就是待匹配的client_id值,不存在名为client_id的键,ele.client_id的写法永远拿不到对应值
  • find回调中错误使用了赋值运算符=而非全等比较运算符===,逻辑完全错误,会直接返回第一个元素
  • 对req.body.client_id做JSON.parse(JSON.stringify())是完全多余的操作,字符串类型不需要深拷贝

正确实现代码

const oauthClients = [
  { "0ADAA2B8": "96eb8c0fbfb31ac43288" },
  { P3CKTGC7: "FKC78N6Plm1Vwjk8KItS" },
];

const client_id = req.body.client_id;
// 匹配逻辑:判断当前对象是否存在以client_id为键的属性
const filtered_value = oauthClients.find((ele) => {
  return Object.hasOwn(ele, client_id);
});
console.log(filtered_value);

如果需要同时拿到匹配到的client secret,可以追加取值逻辑:

const clientSecret = filtered_value ? filtered_value[client_id] : null;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 16:36:04