Home > Web Front-end > JS Tutorial > How Can I Easily Get an Array of JavaScript Object Keys?

How Can I Easily Get an Array of JavaScript Object Keys?

Patricia Arquette
Release: 2024-11-29 12:14:13
Original
581 people have browsed it

How Can I Easily Get an Array of JavaScript Object Keys?

Acquiring JavaScript Object Keys As Array

One requires JavaScript object keys to be present as an array, leading to the usage of loops as follows:

var foo = { 'alpha': 'puffin', 'beta': 'beagle' };
var keys = [];
for (var key in foo) {
    keys.push(key);
}
Copy after login

However, a simpler approach is available.

Using Object.keys

With the Object.keys method, the array of object keys can be obtained concisely:

var foo = { 'alpha': 'puffin', 'beta': 'beagle' };
var keys = Object.keys(foo);
console.log(keys) // ['alpha', 'beta']
Copy after login

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

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template