乐闻世界logo
搜索文章和话题

Get array of object's keys

1个答案

1

In JavaScript, to obtain an array of all keys of an object, you can use the Object.keys() method. This method returns an array containing the names of the object's own enumerable properties, ignoring properties from the prototype chain.

Example:

Suppose we have the following object:

javascript
const person = { name: '张三', age: 30, job: '软件工程师' };

To retrieve all keys of this object, you can do:

javascript
const keys = Object.keys(person); console.log(keys); // Output: ["name", "age", "job"]

In this example, Object.keys(person) returns an array ['name', 'age', 'job'], which contains all keys of the person object.

Usage Scenarios:

This method is highly practical when iterating over object keys, such as checking if an object contains a specific key or organizing data based on keys. For instance, to verify if an object contains a specific property, you can combine Object.keys() with the includes() method:

javascript
if (Object.keys(person).includes('age')) { console.log('Age is: ' + person.age); } else { console.log('No age information provided'); }

This code checks if the person object contains the 'age' key. If it does, it outputs the age; otherwise, it indicates that no age information is provided.

Notes:

  • Object.keys() includes only the object's own enumerable properties and excludes inherited properties.
  • If property names are not strings (e.g., Symbol keys), they are not returned by Object.keys(). In such cases, you can use Object.getOwnPropertyNames() or Reflect.ownKeys() to retrieve all keys, including non-string keys and non-enumerable keys.
2024年6月29日 12:07 回复

你的答案