使用变量

时间:2016-08-24 16:25:38

标签: javascript arrays json

我目前有以下代码,它使用keys变量检索json值产生错误。

var data;
var store;
for (var a in keys){
  for(var b in person){
    data = person[b].keys[a];
    if (data=="1"){
      store += "hit ";
    }
  }
}

json对象即时测试,看起来像:

var person = [
  {
    "Permissions": "Admin",
    "Scope": "Super powers",
    "ReadOnly User": "stuff",
    "Admin User":"1"
  },
  {
    "Permissions": "Read-Only",
    "Scope": "Reading",
    "ReadOnly User": "some stuff",
    "Admin User":"0"
  },
  {
    "Permissions": "Do Guy",
    "Scope": "Labour",
    "ReadOnly User": "many things",
    "Admin User":"1"
  }
];

并使用以下内容检索密钥:

var keys =[];
   if(person.hasOwnProperty(0)){
      for(var prop in person[0]){
         if(person[0].hasOwnProperty(prop)){
           if(prop !== 'Permissions' && prop !== 'Scope'){
             keys.push(prop);
           }
         }
      }
   }

对于具有1

的每个管理员用户密钥,最终结果应该存储两次

2 个答案:

答案 0 :(得分:0)

另一种方法可能是进行两次传递:一次过滤到你想要处理的项目列表(例如:找到管理员用户)然后另一个做实际工作(例如:记录一个"打&#34)



var person = [{
  "Permissions": "Admin",
  "Scope": "Super powers",
  "ReadOnly User": "stuff",
  "Admin User": "1"
}, {
  "Permissions": "Read-Only",
  "Scope": "Reading",
  "ReadOnly User": "some stuff",
  "Admin User": "0"
}, {
  "Permissions": "Do Guy",
  "Scope": "Labour",
  "ReadOnly User": "many things",
  "Admin User": "1"
}];

person
  .filter(function (user) {
    return user['Admin User'] === "1";
  })
  .forEach(function (admin) {
    // here, do what you need to do with the admin users
    console.log(admin);
  })




编辑:我刚看到你对不同答案的评论:"脚本需要是通用的而不是特定的键"

function filterBy(arr, key, val) {
  return arr.filter(function (item) {
    return item[key] === val;
  });
}

filterBy(person, 'Admin User', '1'); // gives a list of the admin users

答案 1 :(得分:0)

仔细看看这一行:

data = person[b].keys[a];

这表示要获取b对象的属性person,然后取其属性"keys",然后取其属性a

显然,person[b]没有名为"keys"的属性。您正在寻找

data = person[b][keys[a]];

换句话说,您从a的名为"keys"的属性中,从名为b的属性中获取person命名的属性。

您要做的是从a中名为keys的属性中取名为b的数组中名为person的属性。