Insert data into an array

I cannot insert data into an array. I want it to be as one array. I want to add 12 months in each row. Below is my code:

var data = {};
for (var i = 0; i < 5; i++) {
    data[i] = {
        Name: "Sample",
        Group: "Sample",
        Offering: "India",
        Type: "Employee",
        subject: "Sample",
        sponser: true
    };

    for (j = 1; j <= 12; j++) {
        var val = "m" + j;
        data.val = j + 1;
    }
}
+4
source share
1 answer
  • Your array- object! If you want it to be array, you need to change var data = {};to var data = [];. But it will work the same, so it doesn’t matter here.
  • You did not declare a variable jin the second loop for. You need to add varbefore it, as in the first loop.
  • index object / array, . data[i] data for.
  • val key object / array, []. val .
  • 1 12. j j + 1, 2 13.

var data = {};                       // this is an object
                                     // if it should be an array write 'var data = [];'

for( var i = 0; i < 5; i++ ) {
    data[i] = {
        Name     : "Sample",
        Group    : "Sample",
        Offering : "India",
        Type     : "Employee",
        subject  : "Sample",
        sponser  : true
    };

    for( var j = 1; j <= 12; j++ ) { // added 'var' before 'j'
        var val = "m" + j;
        data[i][val] = j;            // added '[i]' after 'data'
                                     // changed '.val' to '[val]'
                                     // removed '+ 1' after 'j'
    }
}

console.log(data);
Hide result
+1

Source: https://habr.com/ru/post/1653132/


All Articles