javascript - 如何在对象构造函数中使用 Map 数组函数

标签 javascript arrays

如何使用 map 函数在数据集下拥有 3 个数组,而不是另一个名为“标签”的对象。当我尝试将 map 函数放在“label”之前,就在构造函数中的“dataset”之后时,我遇到了关于出现意外“.”的奇怪错误。点等

预期输出

{
  colors: blue,
  datasets: [
    {
      label: 'car',
      type: 'line',
      data: '1'
    },
    {
      label: 'bus',
      type: 'line',
      data: '5'
    },
    {
      label: 'train',
      type: 'line',
      data: '10'
    }
  ]
}

function Constructor(colors, label, type, data) {
  this.colors = colors;
  this.label = label;
  this.type = type;
  this.data = data;

  this.mainData = {
    colors: colors,
    datasets: [{
      label: label.map((label, i) => ({
        type: type,
        data: data[i]
      }))
    }]
  }
};

var whyYouNoWork = new Constructor('blue', ['car', 'bus', 'train'], 'line', ['1', '5', '10']);

console.log(whyYouNoWork.mainData);

最佳答案

您可以使用函数 map 构建所需的输出:

function Constructor(colors, label, type, data) {
  this.colors = colors;
  this.label = label;
  this.type = type;
  this.data = data;

  this.mainData = { colors, datasets: label.map((label, i) => ( { label, type, data: data[i] } ) ) }
};

var whyYouNoWork = new Constructor('blue', ['car', 'bus', 'train'], 'line', ['1', '5', '10']);

console.log(whyYouNoWork.mainData);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何在对象构造函数中使用 Map 数组函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49432237/

相关文章:

javascript - 如何根据选择器查找对象中元素的值

javascript - 厌倦了 Medium.com 的优质内容。我可以隐藏针对具有特定类的元素的父元素的高级帖子吗?

python - Numpy 根据其值对数组中的元素求和

python - uint8 小端数组到 uint16 大端

javascript - 有没有办法使用相同的形式继续添加到 javascript 数组?

javascript 覆盖居中对齐的模态弹出窗口

java - 在java中填充一个二维数组

使用原型(prototype)方法未定义 Javascript 数组成员变量

javascript - 在javascript中将数组拼接成数组的更好方法

javascript - DataTables 无法读取未定义的属性 'length'