tania saxena tania saxena - 4 years ago 81
AngularJS Question

Iterate an object to find which are the missing numbers and assign a value to it

I have a scenario where I need to iterate over an object which is:

var rating = {
"1": "75%",
"2": "20%",
"3": "10%"
}


and i need to iterate over the rating object and among 1-5 if there are any missing rating i need to assing 0% to it

final output:

var rating = {
"1": "75%",
"2": "20%",
"3": "10%",
"4":"0%",
"5":"0%"
}


i have tried like this

for (var i = 1; i <= 5; i++) {
angular.forEach(vm.rating, function(value, key) {
if (i != parseInt(key)) {
vm.rating[i.toString()] = "0%";
}
});
}


but all the values are changed to 0%

any help would be appreciated.

Answer Source

You don't need to loop twice. You know what predefined keys you need, all you should do is check whether or not a key exist and create it if it doesn't.

for (var i = 1; i <= 5; i++) {
        if (!vm.rating.hasOwnProperty(i.toString())) {
            vm.rating[i.toString()] = "0%";
        }
    }

By doing forEach within the for loop, you are iterating over all keys and comparing with i, and reassigning all values of keys that do not match with i, to "0%". So by the end of the first i, you already have 4/5 of your keys set to "0%"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download