1

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: enter image description here

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?

knot22
  • 2,648
  • 5
  • 31
  • 51
  • 1
    Looks like you need `Array.reduce` – Matt Dec 09 '20 at 17:31
  • I advise against using `.map()` for trivial iteration. At best, you can create an array of key-value pairs and then use `Object.fromEntries()` (you can [use a generator](https://stackoverflow.com/a/64401229/) to map into key-value pairs to feed into `fromEntries` if you want) but a `.forEach()` (or a normal loop) is more straight forward. You can also `.reduce()` into an object. – VLAZ Dec 09 '20 at 17:37

2 Answers2

1

You can use reduce()

const data = [
   { scenario: '328', buckets: 2 },
   { scenario: '746', buckets: 1 },
   { scenario: '465', buckets: 2 }
];
const res = data.reduce((ac, {scenario:s, buckets:b}) => ({...ac, [s]:b}), {});
console.log(res)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
1

You could map the data and create an object from the entries with Object.fromEntries.

const
    data = [{ scenario: '328', buckets: 2 }, { scenario: '746', buckets: 1 }, { scenario: '465', buckets: 2 }],
    result = Object.fromEntries(data.map(({ scenario, buckets }) =>
        [scenario, buckets]
    ));

console.log(result);

Another solution by spreading objects for Object.assign.

const
    data = [{ scenario: '328', buckets: 2 }, { scenario: '746', buckets: 1 }, { scenario: '465', buckets: 2 }],
    result = Object.assign(
        {},
        ...data.map(({ scenario, buckets }) => ({ [scenario]: buckets }))
    );

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392