Convert An Array’s Values To Object’s Keys – JavaScript

You can convert an array’s values to object’s keys in JavaScript using any of these methods –

  1. Use the Array.reduce() method to convert an array’s values to object keys.
  2. Use the Array.forEach() method to convert an array’s values to object keys.

Let’s look at each of these methods in detail below.

convert an array's values to object's keys in javascript

Use Array.reduce() To Convert An Array’s Values To Object’s Keys

You can use the Array.reduce() method to convert an array’s values into object keys. The reduce() method accepts a callback function as its first argument and runs that callback function on each element of the array, resulting in a single output value.

For example –

var arr = [‘a’, ‘b’, ‘c’];

var obj = arr.reduce(function(acc, val) {

  acc[val] = ";

  return acc;

}, {});

console.log(obj); // { a: ", b: ", c: " }

In the above code, we have an array called arr that contains three elements – ‘a’, ‘b’ and ‘c’. We use the Array.reduce() method to convert these values into object keys. The reduce() method accepts a callback function as its first argument. This callback function has two arguments – acc and val. Here, acc is the accumulator that stores the output value and val is the current value being processed in the array.

In each iteration of the reduce() method, we add a new key to our object with a value of an empty string. Finally, we return this object.

We can also use the spread operator (…) to make our code more concise as follows –

var arr = [‘a’, ‘b’, ‘c’];

var obj = arr.reduce((acc, val) => ({...acc, [val]:"}), {});

console.log(obj); // { a: ", b: ", c: " }

Use Array.forEach() To Convert An Array’s Values To Object’s Keys

You can also use the Array.forEach() method to convert an array’s values into object keys. The forEach() method accepts a callback function as its first argument and runs that callback function on each element of the array. It doesn’t return any value.

For example –

var arr = [‘a’, ‘b’, ‘c’];

var obj = {};

arr.forEach(function(val) {

  obj[val] = ";

});

console.log(obj); // { a: ", b: ", c: " }

In the above code, we have an array called arr that contains three elements – ‘a’, ‘b’ and ‘c’. We use the Array.forEach() method to convert these values into object keys. The forEach() method accepts a callback function as its first argument. This callback function has one argument – val which is the current value being processed in the array.

In each iteration of the forEach() method, we add a new key to our object with a value of an empty string. Finally, we log this object to the console.

Conclusion

In this article, we saw how to convert an array’s values to object keys in JavaScript using different methods. You can choose any of these methods depending on your use case.

Leave a Reply