繁体   English   中英

如何从另一个数组中的 JSON 对象中提取值?

[英]How can I pull a value from a JSON object from within another array?

我的问题标题可能不是描述这个问题的准确方法,但它是我能想到的最好方法。 我会让这变得非常简单——我试图从下面的 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”的配对名称来访问该值。 我不确定这是否可能。

问题是我不确定变量是否总是在索引 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'))

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM