Emiliano Maccaferri Emiliano Maccaferri - 3 months ago 9
Javascript Question

Check if object doesn't contain a value not working (JS)

I'm having an hard time solving this problem.


For some reason .hasOwnProperty() is not working.

What I want to do is to create a new object (inside another array) when a value (inside an array) doesn't exist in the array I'm currently looping.

I don't know why, but the first condition gets looped everytime, instead of being looped only when the condition is satisfied.

P.S I'm looping into JSON. Example of JSON I'm parsing

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 (!resArray[j]["name"].hasOwnProperty(keys[i])) {
resArray[j]["name"] = keys[i];
resArray[j]["value"] = "None";
statsArray.push({
"name": resArray[j]["name"],
"value": resArray[j]["value"]
});
}
if (resArray[j]["name"] === (keys[i])) {
statsArray.push({
"name": resArray[j]["name"],
"value": resArray[j]["value"]
});
}
}

}


Feel free to ask for clarifying.

Answer

if (!resArray[j]["name"].hasOwnProperty(keys[i])) {

Obviously this statement is wrong. your resArray[j]["name"] is string, not object. In usual you want to check if one object has some enumable property to use hasOwnProperty method.

Comments