我可以通过不同的方式添加我的JavaScript数组

Joh*_*ohn 1 javascript arrays typescript

我有一个以下格式的数组.

timeSeries = [{ key: 'Time Series Data',
                values: [ { 'label': '01/01', 'value': 20 } ] }];
Run Code Online (Sandbox Code Playgroud)

现在我有的typescript对象具有我需要映射到标签值和值的属性.

export interface Plot {
  dateLabel: string;
  x: number;
}
Run Code Online (Sandbox Code Playgroud)

我的plotArray如下

plotArray =   [ { 'label': '01/03', 'value': 30 }, { 'label': '01/04', 'value': 40 }];
Run Code Online (Sandbox Code Playgroud)

有什么不同的方法可以将我的plotArray添加到javascript中timeSeries中的值?

one*_*man 6

您可以通过多种不同方式实现此目的,例如:

  1. 使用concat

    timeSeries.values = timeSeries.values.concat(plotArray);

  2. 使用lodash的 concat函数

    timeSeries.values = _.concat(timeSeries.values, plotArray);

  3. 使用ES6 传播运算符:

    timeSeries.values = [...timeSeries.values, ...plotArray];

    要么

    timeSeries.values.push(...plotArray);

  4. 最后,您可以遍历plotArray并逐个推送它.

    plotArray.forEach(function(plot) { timeSeries.values.push(plot) });