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:
javascriptconst person = { name: '张三', age: 30, job: '软件工程师' };
To retrieve all keys of this object, you can do:
javascriptconst 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:
javascriptif (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 useObject.getOwnPropertyNames()orReflect.ownKeys()to retrieve all keys, including non-string keys and non-enumerable keys.