0

I'm getting an error that says "cannot set property of undefined".

vm.dtr1 = {}; // maybe I'm initializing this wrong ?
vm.dtr1.date1 = {}; // maybe I'm initializing this wrong ?

for(var x=0; x<5; x++){
  vm.dtr1[x].date1 = new Date(days[x]); //getting undefined value
}
halfer
  • 19,824
  • 17
  • 99
  • 186
code.cycling
  • 1,246
  • 2
  • 15
  • 33

5 Answers5

3

vm.dtr is an object, but you are trying to use it as an array by accessing the index. Which will obviously undefined.

You need to declare vm.dtr as an array of type dtx.

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
2

You need to change it to be an array, then before assigning a property it must be initialized.

vm.dtr1 = []; // make it an array

for(var x=0; x<5; x++) {
   vm.dtr1[x] = {}; // initialize it first
   vm.dtr1[x].date1 = new Date(days[x]);
}

Or in better way

vm.dtr1 = [];

for(var x=0; x<5; x++) {
   vm.dtr1[x] = { date1:  new Date(days[x])};
}
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
1

Try following changes will suely work

vm.dtr1 = []; // change here
//vm.dtr1.date1 = {}; // remove this

for(var x=0; x<5; x++){
  vm.dtr1[x] ={}
  vm.dtr1[x].date1 = new Date(days[x]); //
}
Neha Tawar
  • 687
  • 7
  • 23
0

The problem is that the possible values of x are not correct keys for vm.dtr1.

You may want to use for...in loop instead:

for(var x in vm.dtr1) {
  if (vm.dtr1.hasOwnProperty(x)) {
    vm.dtr1[x] = new Date(days[x]);
  }
}

I still don't know what days is. So, you need to figure that out. For more details about iterating over an object, see this post.

31piy
  • 23,323
  • 6
  • 47
  • 67
0

I think you might need to do it like this

var vm = {}; vm.dtr1 = []; 
var day = ['7/7/2012','7/7/2012','7/7/2012','7/7/2012','7/7/2012']
  vm.dtr1[x] = {};
  vm.dtr1[x].date1 = new Date(days[x]);
}

Still don't know what days is, i did is as expected input for Date constructor