Here is a representative sample of data from a larger dataset in a project:
const data = [
{ scenario: '328', buckets: 2 },
{ scenario: '746', buckets: 1 },
{ scenario: '465', buckets: 2 }
];
There is a need to reformat the data into an object with the scenario value as the key and the bucket value as the value, like this:
I have been able to achieve this outcome by using .forEach
like so:
const reformattedData = {};
data.forEach(o => {
reformattedData[o.scenario] = o.buckets;
});
but I suspect there is a more concise way to accomplish the same output. I have tried .map
as follows
const reformattedData = data.map(o => ({ [o.scenario] : o.buckets}));
but it doesn't give the intended output. Instead it gives [{328: 2}, {746: 1}, {465: 2}]
. What needs to be modified in the .map()
version to attain the desired output?