I am looking to verify the absence of a specific value in the given object by filtering an array of strings.
My goal is to determine if the values within the keys
array are present in the JSON object I am iterating through. If any of the values are missing, I need to take another action, but only if the non-existent value (in resArray
) is part of the keys
array.
This is what I have attempted:
var keys = [
"total_kills",
"total_deaths",
"total_planted_bombs",
"total_defused_bombs",
"total_kills_knife",
"total_kills_headshot",
"total_wins_pistolround",
"total_wins_map_de_dust2",
"last_match_wins",
"total_shots_fired",
"total_shots_hit",
"total_rounds_played",
"total_kills_taser",
"last_match_kills",
"last_match_deaths",
"total_kills_hegrenade",
];
var resArray = stats.playerstats.stats;
var statsArray = [];
for (var i = 0; i < keys.length; i++) {
for(var j = 0; j < resArray.length; j++){
//if the value in keys array exists, do something
if(resArray[j]["name"] === keys[i]){
//do something
}
if(<value doesn't exist)>)
//do something else.
}
}
Solution:
function contains(obj, key, value) {
return obj.hasOwnProperty(key) && obj[key] === value;
}
var resArray = stats.playerstats.stats;
var statsArray = [];
for (var i = 0; i < keys.length; i++) {
resArray.some(function(found){
if(contains(found, "name", keys[i])){
statsArray.push(found);
}
});
if(typeof statsArray[i] == 'undefined'){
console.log("Not present in array: " + keys[i]);
statsArray.push({"name": keys[i], "value": 'None'});
}
}
Appreciation to everyone who contributed to this discussion thread.