1

I have this response from my ajax

and this is my configs.objects

configs.objects    = ['Mexico','Brazil','Spain','Italy','USA'];

enter image description here

(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.

code-8
  • 54,650
  • 106
  • 352
  • 604
  • Does this answer your question? [JavaScript - cannot set property of undefined](https://stackoverflow.com/questions/7479520/javascript-cannot-set-property-of-undefined) – Heretic Monkey Jan 30 '20 at 19:21

4 Answers4

2

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]
});
apsillers
  • 112,806
  • 17
  • 235
  • 239
1

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

Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
1
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;

}
xana
  • 499
  • 3
  • 13
1

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.

Optiq
  • 2,835
  • 4
  • 33
  • 68