在数组的键名中搜索名称并恢复该键值

时间:2017-12-02 04:52:30

标签: javascript

我对MY关于访问复杂键名值的问题得到了很好的答案,但是我发现我可能无法依赖该键的总复杂名称 - 它可能会改变 - 但是我是对关键名称中的最后一个字充满信心,即"角色"。

数组如下 - 从控制台获取:

{
  "http://schemas.microsoft.com/ws/2008/06/identity/claims/role": "Admin",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "admin",
  "nbf": 1512187433,
  "exp": 1512187453,
  "iss": "SuperAwesomeTokenServer",
  "aud": "http://localhost:3000/"
}

除了名称"角色"我不能依赖href是相同的。我不能依赖它目前坐在第一位的事实。

如何检查所有关键名称是否存在" role"埋在名字中,然后返回关键值?

2 个答案:

答案 0 :(得分:1)

尝试以下方式:

var data = {
  "http://schemas.microsoft.com/ws/2008/06/identity/claims/role": "Admin",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "admin",
  "nbf": 1512187433,
  "exp": 1512187453,
  "iss": "SuperAwesomeTokenServer",
  "aud": "http://localhost:3000/"
};

for(var key in data){
  if(key.includes('role')){
    console.log(data[key]);
  }
}

答案 1 :(得分:0)

下面循环遍历对象并返回一个数组,其中键包含' role'。



var obj = {
  "http://schemas.microsoft.com/ws/2008/06/identity/claims/role": "Admin",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "admin",
  "nbf": 1512187433,
  "exp": 1512187453,
  "iss": "SuperAwesomeTokenServer",
  "aud": "http://localhost:3000/"
};

  var arr = [];
for(var key in obj){
  if(key.indexOf('role') !== -1){
    arr.push(obj[key])
  }
}

console.log(arr);