JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to convert array's values to object keys in JavaScript?

To convert an array's values to object keys, use the forEach() method.

  1. First, create an empty object that will store array values as the keys.
  2. Call the forEach() method to loop through the array.
  3. On each iteration, use the array element as a key of the object and assign an empty string ("") to it.

In this way, the object will have all the array elements as its keys.

let arr = ['firstName', 'lastName', 'salary'];
let employee = {};

arr.forEach(element => employee[element] = "");

console.log(employee); //{firstName: '', lastName: '', salary: ''}

In this example, the employee object is empty, and after executing the forEach() method, it has all the array values as the keys.

Another way to convert the array's values to object keys is to use the reduce() method and the spread operator.

The reduce() method accepts two parameters, reducer and initial value.

The reducer is the callback function that is called for each element of the array. It takes two arguments, an accumulator and a current processing element. When you pass an empty object as the value of the initial value parameter, that value is assigned to the accumulator. On each iteration, you assign the array value as the object's key and merge it with the accumulator using the spread operator.

In the final iteration, the reduce() method returns the accumulator's value that will have array elements as the object keys.

let arr = ['firstName', 'lastName', 'salary'];
let employee = {};

employee = arr.reduce((acc, curr) => {
  return {...acc, [curr]: ""};
}, {});

console.log(employee); //{firstName: '', lastName: '', salary: ''}
accumulator currentValue returned value
1st Iteration {} 'firstName' {firstName: ''}
2nd Iteration {firstName: ""} 'lastName' {firstName: '', lastName: ''}
3rd Iteration {firstName: '', lastName: ''} 'salary' {firstName: '', lastName: '', salary: ''}

Recommended Posts