下面是我的代码,我试图将值从“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/