[Chartjs]-How to map json array to two different array for chart

2๐Ÿ‘

โœ…

You can use reduce() to transform the data in required format.

Iterate on given data and if an item with current label exists, then append values to its data array, if not create a new array item with current values.

let input = [
   { "label": "city-1", "data1": 200, "data2": 60 },
   { "label": "city-2", "data1": 450, "data2": 40 },
   { "label": "city-3", "data1": 950, "data2": 78 },
];

let result = input.reduce((acc, curr) => {
  acc.labels = acc.labels || [];
  acc.labels.push(curr.label);
  acc.data = acc.data || [];

  Object.entries(curr).forEach(([key, value]) => {
    if (key !== "label") {
      let item = acc.data.find(item => item.label === key);
      if (item) {
        item.data.push(value);
      } else {
        acc.data.push({
          "data": [value],
          "label": key
        });
      }
    }
  });

  return acc;
}, {});

let labels = result.labels;
let data = result.data;

console.log("Labels", labels);
console.log("Data", data);

1๐Ÿ‘

You can find here a working script:

const list = [
   { "label": "city-1", "data1": 200, "data2": 60 },
   { "label": "city-2", "data1": 450, "data2": 40 },
   { "label": "city-3", "data1": 950, "data2": 78 },
]

const result = list.reduce((acc, item) => {

      const label = item['label'];
      acc[0].push(label);

      const keys = Object.keys(item).filter(key => key !== 'label');
      keys.forEach(key => {
        let labelItem = acc[1].find(value => value.label === key);
        if (!labelItem) {
          acc[1].push({ label:key, data: [item[key]] });
        } else {
          labelItem.data.push(item[key]);
        }
      });

      return acc;
    }, [[], []]);

console.log(result)

For typescript, you will need to add the type.

Leave a comment