简体   繁体   English

Angular - 如何将 Object 转换为数组

[英]Angular - How can i transform an Object into an Array

I'm working on a line chart of ChartJS library.我正在制作 ChartJS 库的折线图。 I have this object and I would like to transform it in an array, because I want to use its data on it.我有这个 object 并且我想将它转换为一个数组,因为我想在它上面使用它的数据。 Searching on the net I found that map it's the easiest way to do that but I can't actually use it on Object, but only on arrays.在网上搜索我发现 map 这是最简单的方法,但我实际上不能在 Object 上使用它,但只能在 arrays 上使用。 How can i convert it in an array or simply use the json data on the line chart?如何将其转换为数组或仅使用折线图上的 json 数据? That's the json object i have right now.这就是我现在拥有的 json object。

{labels: Array(2), values: Array(2)}
labels: (2) ["sales-be", "sales-mw"]
values: (2) [48, 8]

i tried like this but it gives me errors:我试过这样,但它给了我错误:

var labels = this.errorsList.map(function (e) {
      return e.labels;
    });

    var datas = this.errorsList.map(function (e) {
      return e.values;
    });

TypeError: this.errorsList.map is not a function类型错误:this.errorsList.map 不是 function

The properties are already arrays.属性已经是 arrays。 So you could access them directly.所以你可以直接访问它们。

Try the following尝试以下

export class AppComponent {
  errorsList = {
    labels: ["sales-be", "sales-mw"],
    values: [48, 8]
  };

  ngOnInit() {
    this.chartData = [{
      data: this.errorsList.values,
      label: 'Sales',
      fill: false
    }];

    this.chartLabels = this.errorsList.labels;

    this.chartColors = [{
      backgroundColor: 'rgba(0, 0, 0, 0)',
      borderColor: 'rgba(255, 15, 15, 1)'
    }];
  };
}

Template模板

<div id="chart-container">
    <canvas #myCanvas id="canvas" baseChart [chartType]="chartType" [datasets]="chartData" [labels]="chartLabels" [colors]="chartColors" [options]="chartOptions"></canvas>
</div>

Working example: Stackblitz工作示例: Stackblitz

Here the errorsList is defined with hard values only for illustration.这里的errorsList是用硬值定义的,只是为了说明。 You don't have to define it in your code.您不必在代码中定义它。

Again this code is an example and it's only here to illustrate how to use the properties from your object, nothing more.同样,此代码是一个示例,仅用于说明如何使用 object 中的属性,仅此而已。

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

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