Reset array value inside angular.foreach loop
I have an array of empty objects like this:
var a = [ {}, {}, {}, {}, {}, {} ];
And an array of properties:
var colors = ["red", "green", "blue"];
I need to assign each color in "colors" to each element of array "a" with angular foreach. But the length of the array "a" is greater than the length of "colors". I want to assign colors "in a circle". So the result should be like this:
var a = [
{color: "red"},
{color: "green"},
{color: "blue"},
{color: "red"},
{color: "green"},
{color: "blue"},
{color: "red"}
];
angular.forEach(a, function(elem, index) {
if (a.length > colors.length) {
// .......
}
elem.color = colors[index];
});
Question: is there any way to reset the foreach index to start looping the "colors" array from the beginning? thanks for the help
+3
source to share
3 answers
try a javascript function map
like this
var a = [ {}, {}, {}, {}, {}, {}, {} ];
var colors = ["red", "green", "blue"];
a = a.map(function(o,i){
var color = (colors[i]) ? colors[i] : callFunc(i);
o.color =color;
return o;
function callFunc(i){
var diff = (i - colors.length)% (colors.length)
return colors[diff]
}
})
console.log(a)
+3
source to share