简体   繁体   English

为什么不能将这些其他数据推入阵列?

[英]Why can't I push this additional data into my array?

I'm making an API call and here is the response 我正在进行API调用,这是响应

在此处输入图片说明

As you can see, key 0 & 1 have NULL for their 'outcome_status' whereas key 2 is populated. 如您所见,键0和1的“ outcome_status”为NULL,而键2为填充键。 The number of returned results is dynamic 返回结果的数量是动态的

I wish to loop the results and push the 'category' & 'location' details into the array and if 'outcome_status' isn't NULL then I wish to add that data into the same array. 我希望循环结果并将“类别”和“位置”详细信息推入数组,如果“ outcome_status”不为NULL,则希望将该数据添加到同一数组中。

The problem is, within the IF statement that checks if outcome_status is null, I can't assign the forloop var i; 问题是,在检查result_status是否为null的IF语句中,我无法分配forloop var i; variable as the key for mapData where I use .push() the second time. 变量作为mapData的键,第二次使用.push()

line:68 Uncaught TypeError: Cannot read property 'push' of undefined 行:68未捕获的TypeError:无法读取未定义的属性“ push”

var mapData = [];
function getPolApi(year,month,lat,lng,mapData) {
    $.ajax({
    url : "https://data.police.uk/api/crimes-at-location?date="+year+"-"+month+"&lat="+lat+"&lng="+lng,
    type : "get",
    async: false,
    success : function(data) {
      console.log(data);
      mapData = [];// Empty the array of old results
      for(var i = 1; i < data.length; i++) {      

EDIT: I want to do this. 编辑:我想这样做。

            mapData.push([
              data[i]['category'],
              data[i]['location']['street']['name'],
              data[i]['outcome_status']['category'],
              data[i]['outcome_status']['date']
            ]); 

But if there is no outcome_status then it will fail... So I added the second part into a conditional instead 但是,如果没有outcome_status那么它将失败...因此,我将第二部分添加到有条件的中

         if(data[i].outcome_status != null) { 

          //In order to access the original array by key,
         // I wish to the use the forloop iteration otherwise 
         //mapData.push() will add the data as NEW arrays instead of adding on to the end of the existing arrays.

          //Why can't I use the current index for the key here?

              mapData[i].push([ //line 68

              data[i]['outcome_status']['category'],
              data[i]['outcome_status']['date'],
            ]);
         }
           heatmapData.push(new google.maps.LatLng(data[i].location.latitude,data[i].location.longitude));
      }

      console.log(mapData);
       //Add results into view

          for(var i = 0; i < mapData.length; i++) {
             var fill = '<div class="row resu"><div class="col-xs-2 number"><h5>'+[i+1]+'</h5></div><div class="col-xs-10"><p class="text-primary">Type of crime: <span class="text-strong">'+mapData[i][0]+'</span></p><p class="text-primary">Location specifics: <span class="text-strong">'+mapData[i][1]+'</span></p></div></div>';
            $('.output').append(fill);

          }//endforloop

          //Move the map into view of the heatmaps
          moveMap(lat,lng);
          //Add the heatmaps
          addHeatMap();

      // console.log(mapData);
    },
    error: function(dat) {
       console.log('error');
    }
 });

The Issue: 问题:

Here, you initialize i as 1: 在这里,您将i初始化为1:

for(var i = 1; i < data.length; i++) {

You then push one item to mapData[] : 然后,您将一项推送到mapData[]

mapData.push([
    data[i]['category'],
    data[i]['location']['street']['name'],
]);

A couple lines later, you try to access mapData[i] ... 几行后,您尝试访问mapData[i] ...

mapData[i].push([
    data[i]['outcome_status']['category'],
    data[i]['outcome_status']['date'],
]);

This is trying to access mapData[1] , but mapData[] only has one item at this point. 这正在尝试访问mapData[1] ,但是mapData[]只有一项。 You need mapData[0] . 您需要mapData[0]


The Solution: 解决方案:

Try simply changing your i to initialize as 0 instead of 1 : 尝试简单地将您的i更改为0而不是1进行初始化:

for(var i = 0; i < data.length; i++) {

If this is not sufficient and data[] needs to be a 1-index, then perhaps mapData[i-1] instead of mapData[i] would suit your needs. 如果这还不够,并且data[]需要为1索引,那么也许mapData[i-1]而不是mapData[i]会适合您的需求。

Some issues: 一些问题:

  • Your for loop starts with i equal to one, so even after the first push, mapData[i] does not yet exist, so applying push to that makes no sense. 您的for循环以i等于1开始,因此即使在第一次推送之后, mapData[i]仍然不存在,因此将push应用于该值是没有意义的。
  • If you want to push additional elements to an existing array, you should not add those additional elements as part of an array, but provide them as separate arguments to push . 如果要将其他元素push送到现有数组,则不应将这些其他元素添加为数组的一部分,而应将它们作为单独的参数提供给push

Furthermore, the code becomes a bit more functional when use array methods like map . 此外,当使用诸如map类的数组方法时,代码将变得更具功能性。

Here is how the part to fill mapData and heatmapData could look like: 这是填充mapDataheatmapData的部分的样子:

// Create a new array, with nested arrays: one per data item
mapData = data.map(function (item) {
    // Use a local variable to build the sub-array:
    var arr = [
      item.category,
      item.location.street.name,
    ];
    if (item.outcome_status) { // add 2 more elements if they exist
        arr.push( // note: no square brackets here
            item.outcome_status.category,
            item.outcome_status.date,
        );
    }
    // Add it to `dataMap` by returning it to the `map` callback:
    return arr;
});

// Extend the heatmap with additional locations
heatmapData = heatmapData.concat(data.map(function (item) {
    return new google.maps.LatLng(item.location.latitude,item.location.longitude);
}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM