rewrite array to object where index is the key in javascript

To rewrite an array into an object in JavaScript where the indices become the keys, you can use a combination of the reduce() method and destructuring.

Here's an example code snippet:

index.tsx
const arr = ["apple", "banana", "orange"];
const obj = arr.reduce((acc, curr, index) => {
  return {...acc, [index]: curr};
}, {});

console.log(obj); // Output: {0: "apple", 1: "banana", 2: "orange"}
201 chars
7 lines

In the above code, we first define an array arr. We then use the reduce() method to iterate over the array and create a new object obj.

The reduce() method takes two parameters: a callback function and an initial accumulator value. In our example, the accumulator value is an empty object {}.

In the callback function, we destructure the current array element and its index. We then use the index as the key and the array element as the value in a new object. We use the spread ... operator to merge the new object with the accumulator object.

Finally, we log the new object obj to the console. The output shows that the indices have been transformed into keys in the new object.

gistlibby LogSnag