Modelo

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

How to Make toArray() Not Return Object in JavaScript

Oct 05, 2024

In JavaScript, the toArray() method is used to convert object-like structures into arrays. However, by default, the toArray() method returns an object instead of an array. This can be inconvenient when you specifically need an array. Luckily, there are a few simple ways to make toArray() not return an object in JavaScript.

Use Object.values() Method:

One way to convert an object to an array in JavaScript is by using the Object.values() method. This method returns an array containing the property values of the given object in the same order as a for...in loop. Here's an example of how to use the Object.values() method to convert an object into an array:

```

const obj = { a: 1, b: 2, c: 3 };

const arr = Object.values(obj);

console.log(arr); // [1, 2, 3]

```

Use Object.entries() Method:

Another method to convert an object to an array in JavaScript is by using the Object.entries() method. This method returns an array containing the key-value pairs of the given object as arrays. Here's an example of how to use the Object.entries() method to convert an object into an array:

```

const obj = { a: 1, b: 2, c: 3 };

const arr = Object.entries(obj);

console.log(arr); // [['a', 1], ['b', 2], ['c', 3]]

```

Create Custom Function:

If you prefer a custom solution, you can create a function that iterates through the object and pushes its values into a new array. Here's an example of a custom function to convert an object into an array:

```

function customToArray(obj) {

const arr = [];

for (const key in obj) {

arr.push(obj[key]);

}

return arr;

}

const obj = { a: 1, b: 2, c: 3 };

const arr = customToArray(obj);

console.log(arr); // [1, 2, 3]

```

The toArray() method is a convenient way to convert object-like structures into arrays in JavaScript. By using Object.values(), Object.entries(), or a custom function, you can easily ensure that toArray() does not return an object. Try out these methods to efficiently convert objects to arrays in your JavaScript projects.

Recommend