0

For example i've created an array in a for loop:

for (i = 0; i < data.length; i++){
   array[i] = {
     label: bread,
     color: colorArray[i]
   };
 }

In a child for loop i'd like to append more data to this array. What I tried:

for (r = 0; r < data[i].length; r++){

   array[i].push({
      data: breadTypes[r][i]
   });
}

Which throws TypeError : array[i].push is not a function.

array[r] = { data: breadTypes[r][i] }; overwrites the existing data as expected.

Is there a different way to do this? Thanks!

alienwife
  • 70
  • 1
  • 11

3 Answers3

1

Just do like this:

for (i = 0; i < data.length; ++i) {
    array[i].data = breadTypes[i];
}
  • I have 2 bread objects that each has a lot of dataTypes. Thats why I need 2 for loops to first get those 2 bread objects and then add the dataTypes to those objects accordingly.. – alienwife Aug 22 '18 at 10:23
1

Here array[i] is an object and push is an array method which cannot be used on an object but you can create data key in array[i] object

array[r].data = breadTypes[r];

If the second loop is not nested inside the first one then breadTypes[r][i] will throw an error since i will be be available

brk
  • 48,835
  • 10
  • 56
  • 78
0

If i understand correctly, your second for should look like this:

for (r = 0; r < data[i].length; r++){
    array[i].data = breadTypes[r][i];
}
Cata John
  • 1,371
  • 11
  • 19
  • That will re-write `array[i].data` `data[i].length - 1` times. What's the point? You should use `array[i].data.push(breadTypes[r][i])`. And define `array[i].data = []` outside of `for (r = 0; r < data[i].length; r++)` – Alexander N. Morgunov Aug 22 '18 at 09:04