0

Here is a small sample of data that's representative of a larger dataset:

const data = [
    { id: 32, minimum: 200, maximum: 400 },
    { id: 16, minimum: 370, maximum: 390 },
    { id: 85, minimum: 700, maximum: 950 }
];

There is a need to create an object from this data using the id as the key and having the min and max as the value, like so:

enter image description here

The current approach for creating this object is the following -

let object = {};
data.forEach(o => {
    object[o.id] = { min: o.minimum, max: o.maximum }
});
console.log(object);

While this works, it seems like there should be a more concise way of writing this code.

I have experimented with .map() -

const obj = data.map(o => ({[o.id]: { min: o.minimum, max: o.maximum }}));
console.log(obj);

but the output is not in the correct format -

enter image description here

What should be changed in the .map() version to achieve the desired output format?

AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21
knot22
  • 2,648
  • 5
  • 31
  • 51
  • 5
    [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) – Adam Jenkins Dec 18 '20 at 18:57
  • `map()` always creates an array. That's what it does. It takes one array and translates it into another. – Taplar Dec 18 '20 at 18:57
  • [Is performing a mapping operation without using returned value an antipattern?](https://stackoverflow.com/q/56903693) – VLAZ Dec 18 '20 at 19:15

2 Answers2

2
// mapper simply creates the object that you want from the one that you have - id as the key and min and max are the values
const mapper = ({ id, minimum: min, maximum: max }) => ({ [id]: { min, max } });

const obj = data.reduce((acc, obj) => ({
   ...acc,
   ...mapper(obj)
}), {});

EDIT:

While reduce is the right way to do this - you are reduceing an array to a single thing, JavaScript allows you various ways to do things. Here's an alternate solution using map and Object.assign:

const mapper = ({ id, minimum: min, maximum: max }) => ({ [id]: { min, max } });

const obj = Object.assign(...data.map(mapper));
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
2

You could take Object.fromEntries and map the entries.

const
    data = [{ id: 32, minimum: 200, maximum: 400 }, { id: 16, minimum: 370, maximum: 390 }, { id: 85, minimum: 700, maximum: 950 }],
    result = Object.fromEntries(
        data.map(({ id, minimum: min, maximum: max }) => [id, { min, max }])
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392