0

I have a function that loops through an object.

I want data on the form

group1:Array[1,2,3]

group2:Array[4,5,6]

group2:Array[7,8,9]

But instead I get the data on the form

group1:Array[1,2,3,4,5,6,7,8,9]

group2:Array[1,2,3,4,5,6,7,8,9]

group2:Array[1,2,3,4,5,6,7,8,9]

That is it copies the values in the first group that I loop through and then add those values to the rest of the groups and I don't want that. It gets wrong in the function call

for (var resultGroupElement in value[resultKey].DCTRecord.DCT[resultGroup])

And I don't know how to fix it. Do you guys perhapse know how to fix it? I have tried to delete the variables without any luck.

Thanks in advance.

getData: function(value) {
    var dataArray = [];
    var dataArrayHolder = [];

    for (var resultKey in value) {
        var stopTimeConverted = $.extend(true, {}, convertDateToWorkWithAllBrowsers(value[resultKey].StopTime));
        var resultGroups = value[resultKey].DCTRecord.DCT;
        for (var resultGroup in resultGroups) {
            for (var resultGroupElement in value[resultKey].DCTRecord.DCT[resultGroup]) {//Here is where its going wrong

                if (dataArray[resultGroupElement] != null) {
                    var curResultGroupDCT = dataArray[resultGroupElement];
                }
                else {
                    var curResultGroupDCT = [];
                }

                    curResultGroupDCT.push(
                            [
                                new Date(stopTimeConverted),
                                11
                            ]
                            );
                    dataArray[resultGroupElement] = curResultGroupDCT;
                    delete curResultGroupDCT;
            }
            dataArrayHolder[resultGroup] = dataArray;
            delete dataArray;
        }
    }
    console.log(dataArrayHolder);
}
anders
  • 1,535
  • 5
  • 19
  • 43
  • What the original data looks like? – Teemu Sep 10 '14 at 18:11
  • You're both using [`delete`](http://perfectionkills.com/understanding-delete/) and [`for in` loops](http://stackoverflow.com/q/500504/1048572) very wrong. – Bergi Sep 10 '14 at 18:24

2 Answers2

0

"delete" deletes a property of the object, not the object. dataArray is not actually being deleted, and thus will be appended to for any elements within the next group that have the same name/index/whatever as the ones from the previous group.

Use

dataArray = [];

and

curResultGroupDCT = [];

instead.

HamHamJ
  • 435
  • 2
  • 10
0

delete does not do what you think it does.

You keep adding to the same array, replace 'delete dataArray' with 'dataArray = []' to clear it.

    dataArrayHolder[resultGroup] = dataArray;
    dataArray = []; //delete dataArray;
}
folkol
  • 4,752
  • 22
  • 25