Search code examples
javascriptarraysjsonequalsflot

How to check if JSON array is equal to


I am creating pie charts with JSON and Flot. The JS function to create the pie chart receives a JSON array from Django in this format:

[1, 3, 2, 5, 4]

If there is no data, the JSON array is:

[0, 0, 0, 0, 0]

I'm trying to adjust the function so that if there is no data, then the pie will not be plotted and some text will appear instead (e.g. "Nothing to show yet"). So far I have tried:

function loadWeekChart(theData) {
    var blankData = [0, 0, 0, 0, 0];
    if ($.data(theData) == $.data(blankData)){
    $('#week-pie-chart').empty().append('Nothing to show yet');
    } else {
        $.plot($("#week-pie-chart"), theData ,
            {
                series: {
                    pie: { 
                        show: true
                    }
                }
            });
     }
}

The JS doesn't fail, but it neither prints a pie chart (there is no data) nor does it give me the text replacement.

Please can someone show me where I'm going wrong!


Solution

  • Personaly i would do the following heres the psuedo code...

    set boolean to true
    for each element in the JSON
        compare it with blank data element 
        if they are not equal boolean false
        else continue
    return boolean
    

    Then you will know if there same as that function returns true if they are false if they aren't.

    Please let me know if you need help coding this. Shouldn't that hard

    This may also help: Similar Question

    function checkJsons(otherJson,newJson)
    {
        var sameJson = true;
         for (var key in otherJson) {
            if(otherJson[key] != newJson[key]) {sameJson=false;} return sameJson;
         }
    }
    

    That should help, not test though

    A nicer way to do this but harder to read is

    function checkJsons(otherJson,newJson)
    {
      for (var key in otherJson) {if(otherJson[key] != newJson[key]) {return false;}}
      return true;
    }
    
    function pieChartData(theData)
    {
      var blankData = [0, 0, 0, 0, 0];
     if(checkJsons(blankData,theData)){$('#week-pie-chart').empty().append('Nothing to show yet');} else { // do your code here // }
    }