1

An object is created here:

var versionsLegend={}, versionsCounter=1, currentVersionNum=0;

Then in a loop the values should be set - either to a zero value currentVersionNum depending on condition or to other values with a counter versionCounter

The problem is that with the counter it is set as expected, but when the condition is true and it sets the 0 value it turns the object into an Array and wipes out the previous data.

for (var i = 0; i < success.data.data.length; i++) {
    if (success.data.data[i][0].Items.selected) {
        $scope.views.series.push(success.data.data[i][0].Items.id);
        versionsLegend = {
            [success.data.data[i][0].Items.id]: currentVersionNum
        };
    } else {
        versionsLegend = {
            [success.data.data[i][0].Items.id]: versionsCounter
        };
        versionsCounter++;
    }
}    

In the log before this line:

versionsLegend={[success.data.data[i][0].Items.id]:currentVersionNum};

I get Object { 12: 1 } and after Object [ <9 empty slots>, 0 ]

I've omitted the unrelated to the problem parts of the code.

Tried to use .toString() on the object keys - to no avail.

3
  • 4
    How the console prints values is not standardized. Don't worry about it. The value is still an object. Commented Jan 3, 2018 at 16:40
  • 1
    Has nothing to do with converting it to an array, it has to do with you overriding the variable on every iteration. Commented Jan 3, 2018 at 16:46
  • Felix, indeed! It was the console result that left me puzzled and made me make the mistake of overwriting the object. In fact, the resulting array is fine. If you create an answer, I'll mark it as the right one. Commented Jan 3, 2018 at 17:16

1 Answer 1

3

Doing versionsLegend={...}; sets the value of versionsLegend to a new object.

Use versionsLegend[key] = value instead -- that'll set the property on the current versionsLegend object.

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

1 Comment

Ah, yes, of course... My mistake, but it was like that before - I was experimenting with options. Changed it back to: versionsLegend[success.data.data[i][0].MovieScriptsVersions.id]=currentVersionNum; And versionsLegend[success.data.data[i][0].MovieScriptsVersions.id]=versionsCounter; Same problem persists.

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.