I have this response from my ajax
and this is my configs.objects
configs.objects = ['Mexico','Brazil','Spain','Italy','USA'];
(7) [19, 51, 40, 69, 15, 77, 40]
I created a for-loop
var datasets = [];
for (i = 0; i < configs.objects.length; i++) {
console.log(i);
datasets[i]['borderWidth'] = 1;
datasets[i]['hoverBorderWidth'] = 2;
datasets[i]['hoverBorderColor'] = '#fff';
datasets[i]['data'] = response[i];
datasets[i]['label'] = configs.objects[i];
// debugger;
}
console.log(datasets);
I kept getting
Uncaught TypeError: Cannot set property 'borderWidth' of undefined
Why ? Am I doing anything wrong ? I've been staring at this codes for the last 2 hours.
I can't tell why I kept getting that error.
-
Does this answer your question? JavaScript - cannot set property of undefinedHeretic Monkey– Heretic Monkey2020年01月30日 19:21:48 +00:00Commented Jan 30, 2020 at 19:21
4 Answers 4
datasets is an empty array with no elements, and you never add any. Simply ensure that the ith element is initialized as an object fist:
datasets[i] = {};
You could also restructure your code a bit and instead push object literals to datasets for the same result:
datasets.push({
borderWidth: 1,
hoverBorderWidth: 2,
hoverBorderColor: #fff,
data: response[i],
label: configs.objects[i]
});
Comments
var datasets = [];
for (i = 0; i < configs.objects.length; i++) {
let obj = {}
obj['borderWidth'] = 1;
obj['hoverBorderWidth'] = 2;
obj['hoverBorderColor'] = '#fff';
obj['data'] = response[i];
obj['label'] = configs.objects[i];
datasets[i] = obj;
// debugger;
}
Comments
Before you set values, you need to initialize it to an object first:
datasets[i] = {};
datasets[i]['key'] = 'value';
Further reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer
Comments
It's because by using datasets[i] you're approaching it as if that object already exists to grab out of the array and modify; when you're really trying to store those values in that empty array as objects.
The way you handle that is to create a variable to store those properties into then push that object to your array which can look like this.
var datasets = [];
for(i = 0; i < configs.object.length; i++){
var dataObject = {
borderWidth: 1,
hoverBorderWidth: 2,
hoverBorderColor: '#fff',
data: response[i],
label: configs.objects[i]
};
datasets.push(dataObject);
}
console.log(datasets);
Now the datasets variable will have objects with those properties and values which you can now index into.