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
Release: 2024-12-03 14:24:16
Original
942 people have browsed it

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]; });
Copy after login

This will result in:

[11, 22]
Copy after login

With an ES6 arrow function:

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

Or with ES7's Object.values method:

var arr = Object.values(obj);
Copy after login

For a simpler approach using Underscore/Lo-Dash:

var arr = _.values(obj)
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template