Modelo

  • EN
    • English
    • Español
    • Français
    • Bahasa Indonesia
    • Italiano
    • 日本語
    • 한국어
    • Português
    • ภาษาไทย
    • Pусский
    • Tiếng Việt
    • 中文 (简体)
    • 中文 (繁體)

Converting an Array to an Object in JavaScript

Sep 30, 2024

In JavaScript, you can convert an array to an object using the JSON.stringify() and JSON.parse() methods. First, use JSON.stringify() to convert the array to a JSON string. Then, use JSON.parse() to parse the JSON string back into an object. Here's an example:

const array = ['apple', 'banana', 'orange'];

const jsonString = JSON.stringify(array); // '["apple", "banana", "orange"]'

const obj = JSON.parse(jsonString); // {0: 'apple', 1: 'banana', 2: 'orange'}

You can also use Array.reduce() method to convert an array to an object. Here's how:

const array = ['apple', 'banana', 'orange'];

const obj = array.reduce((acc, cur, index) => {

acc[index] = cur;

return acc;

}, {}); // {0: 'apple', 1: 'banana', 2: 'orange'}

These are the ways to convert an array to an object in JavaScript. Depending on your specific needs, you can choose the method that best suits your requirements.

Recommend