Home >Web Front-end >JS Tutorial >How Can I Efficiently Convert a JavaScript Object to an Array?

How Can I Efficiently Convert a JavaScript Object to an Array?

DDD
DDDOriginal
2024-12-03 14:24:16947browse

How Can I Efficiently Convert a JavaScript Object to an Array?

Converting a JS Object to an Array: An Efficient Approach with jQuery

While iterating over a JavaScript object using jQuery's $.each method can convert it to an array, there are more efficient ways to achieve this conversion.

For a functional approach:

var obj = {1: 11, 2: 22};
var arr = Object.keys(obj).map(function (key) { return obj[key]; });

This will result in:

[11, 22]

With an ES6 arrow function:

Object.keys(obj).map(key => obj[key])

Or with ES7's Object.values method:

var arr = Object.values(obj);

For a simpler approach using Underscore/Lo-Dash:

var arr = _.values(obj)

The above is the detailed content of How Can I Efficiently Convert a JavaScript Object to an Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn