Home > OS >  How to format an array as labels and values in JavaScript?
How to format an array as labels and values in JavaScript?

Time:10-31

I'm still new to Angular and I'm trying to get a chart for my data using FusionCharts. FusionCharts uses the following format to get the data.

const chartData = [{
      label: "2021-09-26T00:01:00",
      value: "250"
    },
    {
      label: "2021-09-26T00:02:00",
      value: "251"
    },
    {
      label: "2021-09-26T00:03:00",
      value: "245"
    },
    {
      label: "2021-09-26T00:04:00",
      value: "248"
    },
    {
      label: "2021-09-26T00:05:00",
      value: "251"
    },];

I got two separate arrays as values and labels. How can I convert them to this format.

I tried using dictionaries, but it has {label: value} format that can't be used with FusionCharts

CodePudding user response:

That should just be a simple map() operation:

const labels = ['2021-09-26T00:01:00', '2021-09-26T00:02:00'];
const values = ['250', '251'];

const result = labels.map((label, i) => ({ label, value: values[i] }));

console.log(result);

  • Related