Marco
Marco

Reputation: 501

Simple double for loop

i am trying to create an array like this:

0{
            0 - 2015
            1 - {thema1,thema2,thema3}
 },
1{
            0 - 2016
            1 - {thema1,thema2,thema3}
 }

i take the content out of a sharepoint list with a framework by using the following code lines:

actualYear = 2016;
actualMonth = 9;
columns= [];

    $(document).ready(function(){
        for(var year = 2015; year <= actualYear; year++){

            var element = [];
            element.push(year);


            $SP().list("Workload_"+year).view("Alle Elemente",function(data,viewID) {
                for (var i=0; i<data.fields.length; i++){ element.push(data.fields[i])};
            });
            columns.push(element);
        }
    });

connection is good - and it takes the right data but i have some problems because the code above creates the array like this:

0{
            0 - 2015
            1 - undefined
 },
1{
            0 - 2016
            1 - {thema1,thema2,thema3,thema1,thema2,thema3}
 }

it writes every data.fields into the last subarray. i just don't understand why that happend - has it something to do with the function inside the loop? sure if i use return it writes in the first column subarray with the right data - but it interupts the loop so...

what have i missed?

edit:

var element is to group the loop (year and thema's) the element var should look like: [2015,{thema1,thema2,thema3}]

the columns var is the variable to bring it all together and should look like: [{2015,{thema1,thema2,thema3}},{2016,{thema1,thema2,thema3}}]

my problem is, the topics (thema's) can change in the future so its nota good idea to hardcode those data.fields - thats why i will take it out of the list.

kind regards Proxi

Upvotes: 0

Views: 79

Answers (1)

Pugazh
Pugazh

Reputation: 9561

Try below code.

var actualYear = 2016;
var actualMonth = 9;
var columns = [];

$(document).ready(function() {
  for (var year = 2015; year <= actualYear; year++) {

    var element = [];
    element.push(year);

    $SP().list("Workload_" + year).view("Alle Elemente", function(data, viewID) {
      var arr = []
      for (var i = 0; i < data.fields.length; i++) {
        arr.push(data.fields[i])
      };
      element.push(arr);
    });
    columns.push(element);
  }
});

result in console: enter image description here

Upvotes: 1

Related Questions