Amcharts 4 获取嵌套数组数据 [英] Amcharts 4 getting nested array data

查看:20
本文介绍了Amcharts 4 获取嵌套数组数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 amcharts 4 并想使用我的嵌套数据,我知道 amcharts 不支持嵌套数据,所以我添加了一个 on parseended 事件来更改我的 json 的结构.我可以获取事件的 id 但我无法在对象中添加数组的数据.我可以用我的调试器看到他实际上遍历了嵌套数组的每个对象,但他没有将它们添加到 newDataItem 对象中.

I am using amcharts 4 and wanted to use my nested data, I know amcharts doesn't support nested data so I added a on parseended event to change the structure of my json. I can get the id of the event but I can't add the data of the array in the object. I can see with my debugger that he actually goes through each object of the nested array, but he doesn't add them to the newDataItem object.

我的 JSON:

{{
  "Event": {
    "@id": "45",
    "@name": "SP:StmtCompleted",
    "Column": [
      {
        "@id": "1",
        "@name": "TextData",
        "#text": "SELECT [Object Timestamp], [Object Type], [Object ID], [Change Type] FROM "test".dbo."Object Tracking" WITH(TABLOCK) WHERE [Object Timestamp] > @lastKnownTimeStamp"
      },
      {
        "@id": "3",
        "@name": "DatabaseID",
        "#text": "24"
      },
      {
        "@id": "11",
        "@name": "LoginName",
        "#text": "test\MBS_SERVER-NAV03"
      },
      {
        "@id": "4",
        "@name": "TransactionID",
        "#text": "206618305"
      },
      {
        "@id": "12",
        "@name": "SPID",
        "#text": "77"
      },
      {
        "@id": "10",
        "@name": "ApplicationName",
        "#text": "Microsoft Dynamics NAV Service"
      },
      {
        "@id": "13",
        "@name": "Duration",
        "#text": "25"
      },
      {
        "@id": "14",
        "@name": "StartTime",
        "#text": "2018-09-05T10:24:20.83+02:00"
      },
      {
        "@id": "15",
        "@name": "EndTime",
        "#text": "2018-09-05T10:24:20.83+02:00"
      },
      {
        "@id": "16",
        "@name": "Reads",
        "#text": "2"
      },
      {
        "@id": "17",
        "@name": "Writes",
        "#text": "0"
      },
      {
        "@id": "18",
        "@name": "CPU",
        "#text": "0"
      },
      {
        "@id": "28",
        "@name": "ObjectType",
        "#text": "20816"
      },
      {
        "@id": "35",
        "@name": "DatabaseName",
        "#text": "test"
      },
      {
        "@id": "48",
        "@name": "RowCounts",
        "#text": "0"
      }
    ]
  }
}}

我试图达到的结果的一个例子

{
  "_id": "45",
  "TransactionID": "4",
  "SPID": "12"
  ....
  ....
}

我的组件 .ts:

import { Component, NgZone } from '@angular/core';
import * as am4core from "@amcharts/amcharts4/core";
import * as am4charts from "@amcharts/amcharts4/charts";
import am4themes_animated from "@amcharts/amcharts4/themes/animated";
import { DataSource } from '@amcharts/amcharts4/core';
import { forEach } from '@angular/router/src/utils/collection';

am4core.useTheme(am4themes_animated);

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html',
  styleUrls: ['./chart.component.css']
})

export class ChartComponent {
  constructor(private zone: NgZone) { }

  ngAfterViewInit() {
    this.zone.runOutsideAngular(() => {
      let chart = am4core.create("chartdiv", am4charts.XYChart)

      chart.paddingRight = 30;
      chart.dateFormatter.inputDateFormat = "yyyy-MM-dd HH:mm";

      var colorSet = new am4core.ColorSet();
      colorSet.saturation = 0.4;
      chart.dataSource.url = "https://localhost:44321/api/upload/readFile";
      chart.dataSource.events.on("parseended", function (ev) {
        // parsed data is assigned to data source's `data` property
        var data = ev.target.data;
        var newData = [];
        data.forEach(function (dataItem) {
          var newDataItem = {};
          Object.keys(dataItem).forEach(function (key) {
            if (typeof dataItem[key] === "object") {
              newDataItem["_id"] = dataItem[key]["@id"];
              dataItem[key]["Column"].forEach(function (dataItem) {
                Object.keys(dataItem).forEach(function (key) {
                    newDataItem[dataItem[key]["@name"]] = dataItem[key]["@id"];                                    
                })
              })           
            } else {
              newDataItem[key] = dataItem[key];
            }
          });
          newData.push(newDataItem);
        });
          console.log(JSON.stringify(newData));
          chart.dataSource.data = newData
        });

      chart.data = chart.dataSource.data;

      var categoryAxis = chart.yAxes.push(new am4charts.CategoryAxis());
      categoryAxis.dataFields.category = "_id";
      categoryAxis.renderer.grid.template.location = 0;
      categoryAxis.renderer.inversed = true;


      var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
      dateAxis.dateFormatter.dateFormat = "yyyy-MM-dd HH:mm";
      dateAxis.renderer.minGridDistance = 70;
      dateAxis.baseInterval = { count: 30, timeUnit: "minute" };
      dateAxis.max = new Date(2018, 0, 1, 24, 0, 0, 0).getTime();
      dateAxis.strictMinMax = true;
      dateAxis.renderer.tooltipLocation = 0;

      var series1 = chart.series.push(new am4charts.ColumnSeries());
      series1.columns.template.width = am4core.percent(80);
      series1.columns.template.tooltipText = "{name}: {openDateX} - {dateX}";

      series1.dataFields.openDateX = "fromDate";
      series1.dataFields.dateX = "toDate";
      series1.dataFields.categoryY = "name";
      series1.columns.template.propertyFields.fill = "color"; // get color from data
      series1.columns.template.propertyFields.stroke = "color";
      series1.columns.template.strokeOpacity = 1;

      chart.scrollbarX = new am4core.Scrollbar();

      chart.dataSource.events.on("error", function (ev) {
        console.log("Oopsy! Something went wrong");
      });
    })
  }
}

推荐答案

通过从嵌套项中删除 [key] 来修复它:

Fixed it by removing the [key] from the nested item:

var colorSet = new am4core.ColorSet();
      colorSet.saturation = 0.4;
      chart.dataSource.url = "https://localhost:44321/api/upload/readFile";
      chart.dataSource.events.on("parseended", function (ev) {
        // parsed data is assigned to data source's `data` property
        var data = ev.target.data;
        var newData = [];
        data.forEach(function (dataItem) {
          var newDataItem = {};
          Object.keys(dataItem).map(function (key) {
            if (typeof dataItem[key] === "object") {
              newDataItem["_id"] = dataItem[key]["@id"];
              dataItem[key]["Column"].forEach(function (nestedItem, index) {
                Object.keys(dataItem).map(function () {
                  newDataItem[nestedItem["@name"] + index] = nestedItem["#text"];
                })
              })           
            } else {
              newDataItem[key] = dataItem[key];
            }
          });
          newData.push(newDataItem);
        });
        chart.dataSource.data = newData
        console.log(JSON.stringify(chart.dataSource.data));
        });

这篇关于Amcharts 4 获取嵌套数组数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆