[Chartjs]-How to write better code in es6 for formatting an object with array values

1👍

I’d use reduce and iterate over the Object.entries of each item of graphData, creating an array value at the key in the accumulator if it doesn’t exist yet, then push to that array:

const graphData = [
  {org: 1234, dpt1: 1500, dpt2: 900, dpt3: 107},
  {org: 123, dpt1: 1500, dpt2: 900, dpt3: 1373},
  {org: 123, dpt1: 1500, dpt2: 900,dpt3: 946}, 
  {org: 34634634, dpt1: 1500, dpt2: 900, dpt3: 715}, 
  {org: 123123, dpt1: 1500, dpt2: 900, dpt3: 276}
];
 
const graphdataObj = graphData.reduce((a, obj) => {
  Object.entries(obj).forEach(([key, val]) => {
    if (!a[key]) a[key] = [];
    a[key].push(val);
  });
  return a;
}, {});

console.log(graphdataObj);

Note that forEach is still used, inside the .reduce (but forEach is the most appropriate array method for generic iteration over an array for the purpose of side effects – there’s no more appropriate method than forEach at that point, so it’s not something to worry about).

0👍

Why not reduce without forEach

You can easily avoid using a .forEach as per @CertainPerfomance’s answer by using .reduce. However, you can also avoid using .forEach within the .reduce method as well by using a for ... of loop.

graphData.reduce((data, el) => {
  for (const [key, val] of Object.entries(el)) {
    if (!data[key]) {
      data[key] = [];
    }
    data[key].push(val);
  }
  return data;
}, {});

It’s basically the same idea, but I don’t see the reason to use .forEach when you can use the classic for ... of, which, in my opinion, is much more readable.

Leave a comment