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
}
0

5 Answers 5

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.

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

2 Comments

I've tried to change vm.dtr1 = [] but it still throwing the error.
just doing that won't work, you need to have the objects of type dtx
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])};
}

2 Comments

Thank you so much. its working now i've used your second answer
The second is better. In the first I just want to show the initialization
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]); //
}

Comments

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.

Comments

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

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.