0

Currently I'm writing a program to pull from Police.UK database and here is how the data is interpreted when requesting from the API. The data is passed into a loop and stores the values as shown below. I believe the problem lies in between var outcome = data[i]["outcome_status"]; The problem is the outcome status can either be null or contain two strings these being outcome_status.date and outcome_status.category, How would I differentiate and determine weather the value is null or contains further information.

Thanks!

function create_marker(lat, lng, cat, time, id, street, outcome) {
completed_requests = 1;
document.getElementById("popular_crime").innerText = "";
document.getElementById("num_of_crimes").innerText = "";
var current_lat_lng = [];
current_lat_lng.push(lat, lng, cat, time, id, street, outcome);
chunksize = 7;
var chunks = [];
current_lat_lng.forEach((item) => {
    if (!chunks.length || chunks[chunks.length - 1].length == chunksize)
        chunks.push([]);
    chunks[chunks.length - 1].push(item);
});
for (var z = 0; z < chunks.length; z++) {
    var a = chunks[z];
    var icons = L.icon({
        iconSize: [32, 32],
        iconUrl: 'asset/images/' + a[2] + '.png'
    });
}
switch (a[2]) {
    case 'antisocialbehaviour':
        var popup2 = "<center><br><h2>Anti Social Behaviour</h2><img src=\"asset/images/antisocialbehaviour.png\"height=\"42\" width=\"42\"><h3>Crime Identity Number:</h3><p>" + id + "</p><h3>Month:</h3><p>" + time + "</p><h3>Street Name:</h3><p>" + street + "</p><h2><h3>Outcome:</h3><p>" + outcome + "</p><h2></center>";
        var marker = L.marker(new L.LatLng(a[0], a[1]), {
            icon: icons,
            time: a[3],
            id: a[4],
            street: a[5],
            outcome: a[6]
        });
        marker.addTo(group1).bindPopup(popup2);
        asbcount++
        break;
        break;
    default:
        break;
}

     function get_JSON(url, callback_func) {
       var xmlhttp = new XMLHttpRequest();
       xmlhttp.onreadystatechange = function() {
         var check1 = xmlhttp.readyState == 4 && this.status == 200;
         var check2 = check1 && typeof callback_func === "function";
         if (check2) {
           json_obj = JSON.parse(this.responseText);
           callback_func(json_obj);
         }

       }
       console.log("Getting stats for", url)
       xmlhttp.open("POST", url, true);
       xmlhttp.send();
     }

     function mode(c) {
       var popular_str = "";
       var popular_num = 0;

       for (item in c) {
         num = c[item]
         if (num > popular_num) {
           popular_str = item;
           popular_num = num;
         }
       }

       return popular_str;
     }

     function JSON_callback(data) {
       completed_requests++;
       var data_len = data.length;
       if (data[0] != undefined) {
         for (var i = 0; i < data_len; i++) {
           cat1 = data[i]["category"];
           cat = cat1.replace(/-/g, "");
           cat3 = cat1.replace(/-/g, " ");
           id = data[i]["persistent_id"];
           lat = data[i]["location"]["latitude"];
           lng = data[i]["location"]["longitude"];
           street = data[i]["location"]["street"]["name"];
           time = data[i]["month"];
           var outcome = data[i]["outcome_status"];
           if (cat3 in crimes) {
             crimes[cat3]++;
           } else {
             crimes[cat3] = 1;
           }
           drawChart();
           console.log(data)
           committed = true;
           create_marker(lat, lng, cat, time, id, street, outcome);
           num_of_crimes++;
         }
       }
       document.getElementById("num_of_crimes").innerText = num_of_crimes;
       if (completed_requests == 1) {
         console.log("Requests done");

         //console.log(crimes);
         if (committed) {
           document.getElementById("popular_crime").innerText = mode(crimes);
         } else {
           document.getElementById("popular_crime").innerText = "None";

         }
       }
     }

Here is how the JSON looks when coming from the API

[
   {
      "category":"anti-social-behaviour",
      "location_type":"Force",
      "location":{
         "latitude":"53.746850",
         "street":{
            "id":1289421,
            "name":"On or near Denshaw Drive"
         },
         "longitude":"-1.589005"
      },
      "context":"",
      "outcome_status":null,
      "persistent_id":"a42e1e83ed8055156c1cae319a38b590957de163e8eaeb7884c2b7dd1491056d",
      "id":55436628,
      "location_subtype":"",
      "month":"2017-03"
   },
   {
      "category":"burglary",
      "location_type":"Force",
      "location":{
         "latitude":"53.746074",
         "street":{
            "id":1289411,
            "name":"On or near Hull Street"
         },
         "longitude":"-1.596109"
      },
      "context":"",
      "outcome_status":{
         "category":"Unable to prosecute suspect",
         "date":"2017-03"
      },
      "persistent_id":"906849d248a5b0b26857184a291cbd1e952dfbe62783ad59fdad1c58737386ec",
      "id":55411246,
      "location_subtype":"",
      "month":"2017-03"
   }
]
7
  • What is the function "mode" that you call? Commented Apr 4, 2018 at 21:26
  • It is irrelevant to this part however, it counts the occurrences of crime and total number of crimes in the data. added to original to avoid confusion Commented Apr 4, 2018 at 21:27
  • The reason it seems relevant is that if it returns an object, and you set the innerText of an element to the return value of mode, which happens to be an object, then it will implicitly have .toString() called on it which would result in [object Object]. Commented Apr 4, 2018 at 21:28
  • I'm not setting as a document element. I'm trying to set it in a leaflet marker, will update the case statement for adding the outcome to the marker Commented Apr 4, 2018 at 21:29
  • Wow. is it just me or is this code getting more ridiculous. let us know when you're done adding incomplete, incongruent, apparently wrong (as in mode()), etc. Commented Apr 4, 2018 at 21:35

1 Answer 1

2

You can use Object.assign to set outcome to some default values, when the provided one is null.

var data = [{
    "category": "anti-social-behaviour",
    "location_type": "Force",
    "location": {
      "latitude": "53.746850",
      "street": {
        "id": 1289421,
        "name": "On or near Denshaw Drive"
      },
      "longitude": "-1.589005"
    },
    "context": "",
    "outcome_status": null,
    "persistent_id": "a42e1e83ed8055156c1cae319a38b590957de163e8eaeb7884c2b7dd1491056d",
    "id": 55436628,
    "location_subtype": "",
    "month": "2017-03"
  },
  {
    "category": "burglary",
    "location_type": "Force",
    "location": {
      "latitude": "53.746074",
      "street": {
        "id": 1289411,
        "name": "On or near Hull Street"
      },
      "longitude": "-1.596109"
    },
    "context": "",
    "outcome_status": {
      "category": "Unable to prosecute suspect",
      "date": "2017-03"
    },
    "persistent_id": "906849d248a5b0b26857184a291cbd1e952dfbe62783ad59fdad1c58737386ec",
    "id": 55411246,
    "location_subtype": "",
    "month": "2017-03"
  }
];

for (var i = 0; i < 2; i++) {
  var outcome = Object.assign({
    category: "",
    date: ""
  }, data[i]["outcome_status"]);

  console.log(outcome);
}

And if you want outcome to be just a string you can use

outcome = outcome.date + ":" + outcome.category;

or something else depending on your desires.

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

7 Comments

When I pass outcome to my creat_marker function, when using the switch functions it still displays [object Object] how do I display the object date and category? I updated the first post to display the switch statement thanks.
Use outcome = outcome.date + ":" + outcome.category; before passing it to your function
@AidenMcGree - the switch statement is incomplete.The code is a mess.
What do you expect it to return when it is null?
If possible Null? also when splitting it into this format 2017-04:Unable to prosecute suspect is there a way to make my switch statement read on separate lines instead of inline outcome date: outcome category:
|

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.