Reduce array of objects to an object in JavaScript

Amit Merchant · May 17, 2022 ·

The other day when working with one of the applications, I needed to convert/reduce an array of objects to an object.

Here’s the array that I wanted to reduce.

const ethnicities = [
  {
    id: 1,
    name: 'Asian'
  },
  {
    id: 2,
    name: 'African'
  },
  {
    id: 3,
    name: 'Caucasian'
  }
]

Now, I wanted to convert this to an object where the id of individual array objects would be the key and name would be the value. That’s because I wanted to use the end object as a lookup table based on the id.

To achieve this, I used the Array.reduce() method like so.

const ethnicitiesObject = ethnicities.reduce(
    (previousObject, currentObject) => {
        return Object.assign(previousObject, {
            [currentObject.id]: currentObject.name
        })
    },
{});

console.log(ethnicitiesObject);

// { 1: 'Asian', 2: 'African', 3: 'Caucasian' }

As you can tell, by using the Array.reduce() method, we can reduce the array to an object by initializing the reducer using an empty object ({}) as the second argument of Array.reduce().

And then in the reducer callback, we can work our way up to build the object using the Object.assign() method like how we initially wanted as an end result.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?