generating an array of [month / year] to send to an ajax

1

I'm not sure if I've specified the title correctly, but, come on, I have a url that returns a json with a value from the bank, the value comes this way: "01/2010" through "12/2016". I created a loop that brings me this way: val['01/2010'] .

this is json:

I'dlikeawaynottohavetowritethosedatesstraightintothecode,buttodynamicallygenerateandputitinsidemyloop.followsthefiddle: link

    
asked by anonymous 16.08.2016 / 18:11

2 answers

3

Leandro, to go through a json, just do it like this:

var data = {
  CURSO: "",
  SITUACAO: "",
  TOTAL_FINANCIAMENTO: "",
  SEMESTRES_FINANCIADOS: "",
  VALOR_FINANCIADO_SEM: "",
  DATA_REPASSE: "",
  '01/2010': 0.00,
  '02/2010': 0.00,
  '03/2010': 0.00,
  '04/2010': 0.00,
  '05/2010': 0.00,
  '06/2010': 0.00,
  '07/2010': 0.00,
  '08/2010': 0.00,
  '09/2010': 0.00,
  '10/2010': 0.00,
  '11/2010': 0.00,
  '12/2010': 0.00
};

var isDate = function (text) {
  var date = new Date("01/" + text);
  return date && !isNaN(date) && date != "Invalid Date"
}

for (var key in data) {
  var value = data[key];
  if (isDate(key)) {
    console.log(key, value);
  }
}

Note that in your specific case, in addition to traversing the object keys, you should check whether the key represents a date.

    
17.08.2016 / 13:52
2

Just like @TobyMosque said, so if you want to sequentially iterate dates, you can do so:

var dates = {};

for (var key in val) {
    var index = key.indexOf("/"),
        year = key.substr(index + 1);
    /* checa se o ano já não foi definido e
       checa se key aparenta ser uma data */
    if (!dates[year] && index !== -1)
        dates[year] = {};
}

for (key in val) {
    var index = key.indexOf("/");
    /* checa se key aparenta ser uma data */
    if (index !== -1)
        dates[key.substr(index + 1)][key.substr(0, index)] = val[key];
}

Now you can normally iterate the array dates and concatenate the data of the months:

var html = "";
for (var year of dates) {
    for (var month of year) {
        html += '<td align="right">' + month + '</td>';
    }
}

$('#resultAluno tbody').append('<tr><td>' +
    val.CURSO + '</td> <td>' +
    val.SITUACAO + '</td><td align="right">' +
    val.TOTAL_FINANCIAMENTO + '</td><td align="right">' +
    val.SEMESTRES_FINANCIADOS + '</td><td align="right">' +
    val.DATA_REPASSE + '</td>' + html + "</tr>"
);
    
17.08.2016 / 16:17