Magondu
Magondu

Reputation: 197

Javascript function to check for missing dates on JSON object

I am in my rookie stage learning javascript. I made an API that gets a number of users registered on a certain date and returns this data as a JSON object. Here is a sample of that data

{"myjsonobject": [{"users": 3, "joined": "2013-05-25"}, {"users": 1, "joined": "2013-05-26"}, {"users": 1, "joined": "2013-05-30"}, {"users": 1, "joined": "2013-05-31"}]}

I then parse the data and graph on ChartJS linegraph using the javascript function below

$(document).ready(function()
{
url = "http://mylink/getjson/"
Create_jsonObject(url)
});

function Create_jsonObject(url) {
$.getJSON(url, function (data) {

myJSONObject=data;
var dataSource=myJSONObject.myjsonoject;
var chart = $("#chartContainer").dxChart({

    dataSource: dataSource,

    commonSeriesSettings: {

         argumentField: 'joined'

    },

    series: [

        { valueField: 'users', name: 'users' },

    ],

    argumentAxis:{

        grid:{

            visible: true

        }

    },

    tooltip:{

        enabled: true

     },

     title: 'Volunteer Registration',

     legend: {

        verticalAlignment: 'bottom',

        horizontalAlignment: 'center'

     },

    commonPaneSettings: {

        border:{

            visible: true,

            right: false

        }       

    }

 });


});
};

The function works in charting the JSON data on the linegraph. I would like to incorporate a javascript function that checks for missing dates and inserts 0 users where a date is missing. Thus the graph will plot zero where not date was returned. It should check this against the earliest date returned. Any ideas anyone?

Thanks

Upvotes: 2

Views: 2579

Answers (4)

Roman
Roman

Reputation: 6408

How to fill in missing elements in an array describing a range

Presuming the starting array is already sorted, you might want to copy the first element in the source array into a new one and then iteratively push "default objects" into the destination array or copy from the source array when there is a matching object. Repeat until you reach the end of your range.

To check if there is a matching object, you might want to index first the source array by whatever parameter you want to iterate over (in your case: the "joined" field). This means that this parameter has to be unique.

function getIndex(srcArray, field) {
    var i, l, index;
    index = [];
    for(i = 0, l = srcArray.length; i < l; i++) {
        index[srcArray[i][field]] = srcArray[i];
    }
    return index;
}

This creates a hashmap of your array. Searching an element by it's key (in your case the "joined" field) is very simple:

if(index['2013-06-05'] !== undefined) { 
    /* the element indexed by "2013-06-05" exists */ 
}

Now that you have an index, you can iterate over the range you expect to have. For this, get the first and the last dates in your source array:

//get boundaries
var first = new Date(src[0].joined);
var last = new Date(src[src.length-1].joined);

You also need to know how to construct your default objects:

function createDefault(datestr) {
    return {users: 0, joined: datestr};
}

Now declare a destination array and iterate over the range:

var dest = [];
for(var d = first; d.getTime() <= last.getTime(); d.setDate(d.getDate()+1)) {
    datestr = dateToYMD(d); //dateToYMD is a helper function I declared that formats a date
    if(index[datestr]) {
        //this date exists in your data, copy it
        dest.push(index[datestr]);
    } else {
        //this date does not exist, create a default
        dest.push(createDefault(datestr));
    }
}

I made a jsfiddle that logs the destination array to console. http://jsfiddle.net/uNasR/

Upvotes: 4

Andrey Kuleshov
Andrey Kuleshov

Reputation: 687

I feel there is a little confusion.

Based on code you provided, I think you are using THIS ChartJS: http://chartjs.devexpress.com

:)

With that,I would try one more way to reach your goal: specify explicitely type of your arguments:

argumentAxis: {
    grid: {
        visible: true
    },
    //add this line to specify
    argumentType: "datetime"
},

More info in ChartJS documentation

Upvotes: 0

Abraham Adam
Abraham Adam

Reputation: 633

function fix(json){ 
  var updateUserToDate = function(object){ 
    if (!object['joined']){ object.joined = 0 }
  }
  json.myjsonobject.forEach(updateUserToDate);
  return json;
}

this is my version of it

if your data is still in string format you will need to call JSON.parse on it before you send it to this function, as Ewald Stieger points out

Upvotes: 0

Atomic Star
Atomic Star

Reputation: 5507

Try this:

function fixDate(data)
{
    var myObjects=JSON.parse(data);

    for(var i=0;i<myObjects.length;i++)
    {
      if(!myObjects[i].joined)
         myObjects[i].joined="0";

    }
    return myObjects;
}

Upvotes: 0

Related Questions