5
\$\begingroup\$

I've got such an input object, which I should modify in order to use it with some charts library.

const input = {
  foo: {
    bar: 'biz',
  },
  statistic: {
    "2019-11": {
      A: 11,
      B: 11,
      C: 11,
      D: 11,
      E: 11,
    },
    "2019-12": {
      A: 12,
      B: 12,
      C: 12,
      D: 12,
      E: 12,
    },
    ....
  }
};

My library expects an input like this:

[ 
  { subject: 'A', '2019-11': 11, '2019-12': 12 },
  { subject: 'B', '2019-11': 11, '2019-12': 12 },
  { subject: 'C', '2019-11': 11, '2019-12': 12 },
  { subject: 'D', '2019-11': 11, '2019-12': 12 },
  { subject: 'E', '2019-11': 11, '2019-12': 12 } 
]

And this is my current solution:

const transform = arg => {
  const keys = ['A', 'B', 'C', 'D', 'E'];
  return _.map(keys, key => {
    const data = _.reduce(arg.statistic, (result, value, k) => {
      result[k] = value[key];
      return result;
    }, {});
    return {
      subject: key,
      ...data
    }
  });
}

Any improvements would be very welcome!

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

So you have five data series here right (A through E)? What happens when you have 4 or 6 data series? Do you really want to rewrite your code?

Also, unless you have some reason to do so, lodash seems kind of unnecessary for these sort of simple data transforms these days. I am guessing using ES6 Array.map, Array.reduce and similar would do the same exact thing while also yielding a more fluent, readable style,

\$\endgroup\$
-1
\$\begingroup\$

Using reduce to build a map object sounds wrong. By definition, the word reduce means "to make smaller", but you are using it here "to make bigger". A first step might be:

const data = {};
_.foreach(arg.statistic, (key, value) => data[key] = value);

I don't know whether lodash actually has foreach, it's just to illustrate the idea.

There's probably an even more elegant way to create this map out of the data.

\$\endgroup\$
1
  • \$\begingroup\$ You shouldn't limit yourself by reading too much into the name reduce. It's just one of many names for the same operation. Using it to "reduce" multiple values into a single value (even if that single value ends up being a "larger" object) is exactly what it is meant for. \$\endgroup\$
    – RoToRa
    Commented Jan 30, 2020 at 9:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.