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 it



var a = [ {}, {}, {}, {}, {}, {} ];
var colors = ["red", "green", "blue"];

a.forEach(function(item,key){
    item.color = colors[key % colors.length];
})
console.log(a)

      

+6


source


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)
      

Run codeHide result


+3


source


You can just have a counter i inside the foreach. In every iteration i is like i ++ and when it reaches the length of the array of colors just reset it like i = 0 and color [i] can be used to get the name of the color.

0


source







All Articles