Question

I have an issue I can't quite put my finger on.

var records = dataView.getItems();

for (var i = 0; i < records.length; i++) {
    var date = records[i].RecordCreated;
    records[i].RecordCreated = new Date(parseInt(date.replace('/Date(', '')));
}

records = JSON.stringify(records);

This is a small loop that takes existing data from a SlickGrid dataview and converts the /Date(###)/ format to a proper date format in order to be deserialized on the server. This works fine.

The weird issue is that the var records = dataView.getItems(); definition is acting more like a reference than an individual, unique, object. Consider the following code:

var records = dataView.getItems();

// Debug Code [A]
console.log(records);
console.log(dataView.getItems());

for (var i = 0; i < records.length; i++) {
    var date = records[i].RecordCreated;
    records[i].RecordCreated = new Date(parseInt(date.replace('/Date(', '')));
}

// Debug Code [B]
console.log(records);
console.log(dataView.getItems());

records = JSON.stringify(records);

The console logs at [B] are both identical, where one would expect them to be different. Meaning instead of seeing the second log with unchanged /Date(###)/ format dates, proper date objects are printing.

Even stranger is that at [A] the console logs are printing as if the loop ran asynchronously and finished prior to the console.log() command was called.

This is all wrapped in a function with some conditional statements to do different loops, nothing crazy. What I need to know is how/why the records definition is not working as per usual (a unique variable in memory, that can be edited without affecting the original object).

Solution


So the problem was that records was receiving the original object from the SlickGrid library. What I did to fix the issue was clone the object before assigning it to records.

Clone function:

function clone(obj) {
    if (obj == null || typeof (obj) != 'object')
        return obj;
    var temp = new obj.constructor();
    for (var key in obj)
        temp[key] = clone(obj[key]);
    return temp;
}

Usage:

var __data = dataView.getItems();
records = clone(__data);

Hope this helps anybody else viewing this question in the future.

Was it helpful?

Solution

looks like your records variable is an array being returned from dataView.getItems(). This variable IS a reference to the array object, so changing things on that object will be reflected in all the references to the object.

OTHER TIPS

You should ensure that dataView.getItems() calls Array.protototype.slice on any collection it is returning

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top