I have a function and it works just fine, but codacy inspection says it is bad practice to do so. I understand that it even looks unsafe, but I cannot come up with how to do it another, better, way.
function getCount(i) {
var iCount = iCount || 0;
for (var item in this.items) {
for (var level1 in this.items[item]) {
for (var level2 in this.items[item][level1]) {
for (var level3 in this.items[item][level1][level2]) {
if (this.items[item][level1][level2][level3] == i) {
iCount++;
}
}
}
}
}
return iCount;
}
After Icycool's advices I came up with something more acceptable. I tried to use forEach loop, but it didn't work so I decided to use a fori. Though it is not perfect it'll do for now:
function getCount(i) {
var iCount = iCount || 0;
for (var y = 0; y < this.items["content"].length; y++) {
if (this.items["content"][y]["custom_object"]["id"] === i) {
iCount++;
}
}
return iCount;
}
You can simplify it with a recursive function.
function getCount(i, items) {
var count = 0;
items.forEach(function(item) {
if (item.isArray) count += getCount(i, item);
else if (item == i) count++;
});
return count;
}