How to count the keys of an object that have a specific field value?
-
There is a Permissions object in which the key fields are "True" or "False".
We need to make a function that counts keys whose value is "True".
I tried using Object.values () (although it seems to me that I should use something else), but it does not count the keys.
Here's the code itself:
let Permissions = {canView: "True", canEdit: "False", canPrint: "True"}; function Count() { let count = 0; for (let count of Object.values(Permissions)) { if (Permissions == "True") count++; } alert(count); }
JavaScript Henry Wilcox, Dec 24, 2019 -
let Permissions = {canView: "True", canEdit: "False", canPrint: "True"};
function countTrueKeys(obj) {
let count = 0
for(let key in obj) {
if (obj[key] == 'True') {
count ++
}
}
return count
}
console.log(countTrueKeys(Permissions)) // 2Anonymous -
Your code is just a champion in the number of absurdities, you use count both as a counter and as a variable during iteration, you compare the value of the Permissions object with a string for some reason.
Correct code according to your algorithm:
let Permissions = {canView: "True", canEdit: "False", canPrint: "True"};
function Count() {
let count = 0;
for (let elem of Object.values(Permissions)) {
if (elem === "True") count++;
}
alert(count);
}
But it's easier
const Permissions = {canView: "True", canEdit: "False", canPrint: "True"};
const count = Object.values(Permissions).filter(v => v == "True").length
alert(count)
And it is customary to write variables in js with a small letter (fig knows why, I like the Microsoft style more, but it is accepted this way)Claire Matthews
2 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!