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
Patricia ArquetteOriginal
2024-11-29 12:14:13571browse

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);
}

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']

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:
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
Previous article:Javascript: async/awaitNext article:Javascript: async/await