Array to object conversion in JavaScript

Amit Merchant · May 21, 2022 ·

I was working with a group of checkboxes under a redux-form for one of my applications. So, when I select certain checkboxes here’s the format in which I was getting the value of the checkboxes.

const ethnicities = [
  ,  
  true,
  false,
  true
];

Here the index of this array represents the value of a checkbox. So, checkboxes of values 1, 2, and 3 are selected where the value 2 is checked first and then unchecked later on.

The first index of this array is empty. This means the first checkbox is not yet selected.

Now, before sending it over an API, it was important to convert this array to an object in such a way that the keys will be the array indexes and the value will be the boolean values of these indexes. Because I wanted to potentially use this object as a lookup table.

Here’s how I did it using the Object.assign() method.

const ethnicitiesObject = Object.assign({}, ethnicities);

console.log(ethnicitiesObject);

// { '1': true, '2': false, '3': true }

As you can tell, the Object.assign() method will copy the ethnicities array as an object to the target object which is a blank {} object provided as the first argument, and return us the modified target object.

You may also notice that the method also happily drops the empty index leaving the object as we wanted!

👋 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?