javascript - 如何将数组的列从数组传递到对象字段

标签 javascript angular typescript

下面是我的代码,我试图将值从“dataList”传递到 this.data 对象“labels”、“datasets”-> data;

但是如果创建变量并存储值然后将其传递给标签、数据,我会得到未定义的结果。

这里我的问题是如何设置标签的值,dataList 数组中的数据。

    this.dataList = [['lable1', 200], ['lable2', 300], ['lable3', 500]];

//now I want to access all labels to label, all numbers to data in below instead of static data i want to put data from dataList

    this.data = {
    labels: ['label1', label2, labels3],
    datasets: [
      {
        data: [200, 300, 500],
        backgroundColor: [
          "#FF6384",
          "#36A2EB",
          "#FFCE56"
        ],
        hoverBackgroundColor: [
          "#FF6384",
          "#36A2EB",
          "#FFCE56"
        ]
      }]
  };

我想放置 dataList 中的动态数据,而不是标签中的静态值。

最佳答案

您可以简单地使用 JavaScript 的 Reduce函数开始工作。

Stackblitz DEMO - you can edit this.dataList variable to see the output changing dynamical

this.dataList = [['lable1', 200], ['lable2', 300], ['lable3', 500]];

this.data = {
  labels: this.dataList.reduce((result, item) => {
    result.push(item[0]);
    return result;
  }, []),
  datasets: [
    {
      data: this.dataList.reduce((result, item) => {
        result.push(item[1]);
        return result;
      }, []),
      backgroundColor: [
        "#FF6384",
        "#36A2EB",
        "#FFCE56"
      ],
      hoverBackgroundColor: [
        "#FF6384",
        "#36A2EB",
        "#FFCE56"
      ]
    }]
};

关于javascript - 如何将数组的列从数组传递到对象字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56441746/

相关文章:

mysql - 如何设置查询不接受不存在的字段

TypeScript:无效返回类型转换为任何类型?

c# - C# 中的 charCodeAt() 等价物是什么?

javascript - 使用 jQuery 检测元素内容变化

javascript - 为什么这段 JavaScript 代码返回未定义?

angular - 使用angular在HTTP调用中获取表单数据

javascript - webpack 3 DeprecationWarning : Chunk. 模块已弃用

angular - 使用可移动输入/标签搜索 (Ionic 2)

根据要求分配类(class)的算法

来自 ISO8061 的 Javascript 时间戳