【问题标题】:Can not find an object dynamically from an array无法从数组中动态找到对象
【发布时间】:2021-08-20 06:35:33
【问题描述】:

我必须从正文中可用的 api 调用中获取 client_id。

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

const client_id = JSON.parse(JSON.stringify(req.body.client_id));
const filtered_value = oauthClients.find((ele) => {
  return (ele.client_id = client_id);
});
console.log(filtered_value);

我试过像 return ${ele}+.+`${req.body.client_id}

请大家帮忙..!

【问题讨论】:

  • 请使用严格相等运算符==== 是赋值运算符。 oauthClients.find(ele => { return ele.client_id == client_id })
  • 您能否更清楚地说明什么是客户 ID 和预期结果等问题

标签: javascript node.js arrays google-api-nodejs-client


【解决方案1】:

让这有点困难的是,您的原始数据的结构并不是很好:

鉴于此:

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

没有“client_id”字段 - 客户端 ID 是字段名称,因此很难解析。在 Javascript 中,要对字典的键和值进行通用访问,您可以使用 Object.keys() 和 Object.values() 函数。

我认为您正在寻找给定客户端 ID 的令牌,所以是这样的:

/**
 * Returns the token for the given client ID or undefined if it isn't found
 */
function findToken(clientId: string) {
   const foundElement = oauthClients.find(e => Object.keys(e)[0] === clientId)
   return foundElement 
     ? Object.values(foundElement)[0]
     : undefined
}

【讨论】:

    【解决方案2】:

    您需要改用严格相等运算符

    const filtered_value = oauthClients.find((ele) => {
      return ele.client_id === client_id;
    });
    

    另外oauthClients我们是一个对象,所以你不能真正使用.find遍历它并访问ele.client_id,你需要以某种方式获取对象值并以类似时尚的数组遍历它们

    例如使用Object.keys()

    const filtered_value = Object.keys(oauthClients).find((key) => {
      return oauthClients[key] === client_id;
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-29
      • 1970-01-01
      • 1970-01-01
      • 2020-06-05
      • 1970-01-01
      相关资源
      最近更新 更多