Daxxcat Daxxcat - 3 months ago 9
Javascript Question

Retrieving json data from an array of items using variables

I currently have the following code which produces an error with the keys variable retrieving the json value.

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


The json object im testing with looks like:

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"
}
];


and keys are retrieved with the following:

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);
}
}
}
}


The end result of this should have two hits in store for each Admin User key with a 1

Answer

Another way to do this might be to do two passes: one to filter down to the list of items you want to work on (eg: find the admin users) and then another to do the actual work (eg: record a "hit")

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);
  })

Edit: I just saw your comment on a different answer: "Script needs to be generic and not to a specific key"

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