code.cycling
code.cycling

Reputation: 1274

Angularjs reports "Cannot set property of undefined"

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
}

Upvotes: 0

Views: 188

Answers (5)

Ashish Mishra
Ashish Mishra

Reputation: 94

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

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68635

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])};
}

Upvotes: 2

Neha Tawar
Neha Tawar

Reputation: 705

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]); //
}

Upvotes: 1

31piy
31piy

Reputation: 23859

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.

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222552

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.

Upvotes: 3

Related Questions