knot22
knot22

Reputation: 2768

using .map() instead of .forEach for creating an object

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?

Upvotes: 0

Views: 192

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386660

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; }

Upvotes: 2

Adam Jenkins
Adam Jenkins

Reputation: 55732

// 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));

Upvotes: 2

Related Questions