4

I can't insert data into array. I want it 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
  • data.val = j + 1; need to be data[i].val = j + 1; Commented Aug 31, 2016 at 11:18
  • 1
    @AmrElgarhy that alone will not work, because val is a string and so actually you try to set the property val instead of m1, m2, ... Commented Aug 31, 2016 at 11:24
  • @eisbehr what shall i do Commented Aug 31, 2016 at 11:40
  • Take a look at my answer. I've posted everything very detailed there, with a porking example too. ;) Commented Aug 31, 2016 at 11:41

1 Answer 1

1
  1. Your array is an object! If you want it to be an array, you need to change var data = {}; to var data = [];. But it will work the same way, so it makes no difference here.
  2. You didn't declared the variable j in your second for loop. You need to add var in front of it, like you did in your first loop.
  3. You need to specify the current index of your object / array you want to set the months to. So write data[i] instead of data in your second for loop.
  4. As you want to use the value of val as key in your object / array, you need to put bracers [] around it. Otherwise you will only set the property val of the object.
  5. Your months goes from 1 to 12. You will only need to set j instead of j + 1, because you otherwise write the months from 2 to 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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.