0

I want to loop through an object array but the length property always returns one result less. When I have one dataset, I get 0. When I add another similar dataset, I get 1.

var currDatasets = $(this).data('graph').data.datasets;
console.log(currDatasets);
console.log(currDatasets.length);
// shows '0'
var test = [{ label: 'blah', value: 'blah' }];
console.log(test.length);
// shows '1'

The console output doesn't really differ from the lower result, except that {...} is missing from the [ ]-brackets. However when I use the length property, console.log returns 0.

This is what the console outputs with one datatag:

console result

And this is what it outputs with two datatags:

console result

Kohlkopf
  • 43
  • 5
  • `[{ label: 'blah', value: 'blah' }]` is an array of 1, containing 2 properties. It's different from: `[{ label: 'blah'}, {value: 'blah' }]` – dustytrash Apr 02 '19 at 20:47
  • I'm going to bet you're using Chrome. – Pointy Apr 02 '19 at 20:47
  • Yeah, true. Is this a browser related issue? – Kohlkopf Apr 02 '19 at 20:49
  • use this example: [stackoverflow.com/questions/5223/length-of-a-javascript-object](https://stackoverflow.com/questions/5223/length-of-a-javascript-object) – Rodrigo Rea Apr 02 '19 at 20:51
  • 1
    I guess `datasets` variable is changing over time after you printed to the console. And when you expand that array data in your console, it gets its different value by reference. Try to clone `$(this).data('graph').data.datasets` data by using `slice(0)` and print it to the console – lankovova Apr 02 '19 at 20:53
  • The problem isn't particularly related to the length property. The array seems to contain one item less than expected. I used length as an example. – Kohlkopf Apr 02 '19 at 20:54

0 Answers0