【问题标题】:How can I pull a value from a JSON object from within another array?如何从另一个数组中的 JSON 对象中提取值?
【发布时间】:2021-10-06 03:08:58
【问题描述】:

我的问题标题可能不是描述这个问题的准确方式,但它是我能想到的最好的方式。我会让这变得非常简单——我试图从下面的 JSON 对象中获取 VALUEIWANT 的值。

任何帮助将不胜感激,因为我已经在 w3 学校尝试了 2 小时的各种方法。

我通过硬编码得到的最接近的结果如下:

const x =
  { "UserAttributes": 
    [ { "Name" : "sub"
      , "Value": "54f5cdfb-6ec7-4683-fdasfasdf-2324234234"
      } 
    , { "Name" : "custom:var"
      , "Value": "VALUEIWANT"
      } 
    , { "Name" : "email"
      , "Value": "test.user@email.com"
      } 
    ] 
  , "Username": "testuser"
  } 

const y = x.UserAttributes[1].Value
    // y here would result in VALUEIWANT

问题是我不确定变量是否总是在索引 1。

为清晰而编辑我的目标是能够在我的控制台中检索“VALUEIWANT”的这个值。我需要能够使用“custom:var”的配对名称来访问该值。我不确定这是否可能。

【问题讨论】:

  • 我想在控制台中返回“VALUEIWANT”的值。所以实际值本身。
  • 您想通过关联的“名称”来识别您想要的“值”吗?还是……?
  • 假设该值不是 VALUEIWANT,您将如何确定要选择的 UserAttributes 数组的哪个元素? 是 name==="custom:var" 的那个吗?
  • 我认为他指的是动态查找它,因为索引中会有更多条目。
  • 抱歉解释不好——为了清楚起见,我已经更新了我的帖子。

标签: javascript json typescript parsing


【解决方案1】:

这个问题是我不确定这个变量是否总是 位于索引 1。

您需要使用findIndex (MDN) 查找索引

const x = {
  "UserAttributes": [{
    "Name": "sub",
    "Value": "54f5cdfb-6ec7-4683-fdasfasdf-2324234234"
  }, {
    "Name": "email",
    "Value": "test.user@email.com"
  }, {
    "Name": "custom:var",
    "Value": "VALUEIWANT"
  }],
  "Username": "testuser"
}
const index = x.UserAttributes.findIndex(item => item.Name === "custom:var");

const y = x.UserAttributes[index].Value;

console.log(y);

一个辅助函数如下所示

const x = {
  "UserAttributes": [{
    "Name": "sub",
    "Value": "54f5cdfb-6ec7-4683-fdasfasdf-2324234234"
  }, {
    "Name": "custom:var",
    "Value": "VALUEIWANT"
  }, {
    "Name": "email",
    "Value": "test.user@email.com"
  }],
  "Username": "testuser"
}

function getValue(x, name) {
  const index = x.UserAttributes.findIndex(item => item.Name === name);
  return index === -1 ? null : x.UserAttributes[index].Value;
}

// get email
console.log(getValue(x, 'email'));

// get custom:var
console.log(getValue(x, 'custom:var'))

【讨论】:

    【解决方案2】:

    使用 x.UserAttributes 数组上的Array.find 搜索名称为“custom:var”的项目,并取值:

    const valueYouWant = x.UserAttributes.find(ua => ua.Name === "custom:var").Value;
    

    【讨论】:

      猜你喜欢
      • 2015-03-27
      • 2018-09-22
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 2019-04-22
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      相关资源
      最近更新 更多