Marcer
Marcer

Reputation: 849

Different ways i could append my JavaScript array

I have a array of in the following format.

timeSeries = [{ key: 'Time Series Data',
                values: [ { 'label': '01/01', 'value': 20 } ] }];

now i have typescript object that has properties which i need to map to the label value and value value.

export interface Plot {
  dateLabel: string;
  x: number;
}

my plotArray is as follows

plotArray =   [ { 'label': '01/03', 'value': 30 }, { 'label': '01/04', 'value': 40 }];

What are the different ways i could append my plotArray to values in the timeSeries in javascript?

Upvotes: 1

Views: 88

Answers (2)

onecompileman
onecompileman

Reputation: 940

You can do that in many different ways such as:

  1. Using concat

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

  2. Using lodash's concat function

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

  3. Using ES6 spread operator:

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

    or

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

  4. Lastly you can iterate through the plotArray and push it one by one.

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

Upvotes: 6

reisdev
reisdev

Reputation: 3383

If you're using ES6(or newer), you could use the spread operator(Docs here):

timeSeries.values.push(...plotArray)

Upvotes: 1

Related Questions