📜  object.keys javascript (1)

📅  最后修改于: 2023-12-03 15:33:16.494000             🧑  作者: Mango

JavaScript Object.keys

In JavaScript, Object.keys() is a predefined method that returns an array of a given object's property names.

Syntax

The syntax for using Object.keys() is as follows:

Object.keys(obj)
  • obj - The object whose enumerable properties are to be returned.
Example

Here's how you can use Object.keys() to extract the property names from an object:

const person = {
  name: 'John',
  age: 30,
  job: 'Developer'
};

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

In this example, Object.keys() returns an array containing the property names of the person object.

Notes

Here are some important things to keep in mind when using Object.keys() in your JavaScript code:

  • Object.keys() only returns the enumerable properties of an object. Non-enumerable properties are not returned.

  • The order of the property names returned by Object.keys() is not guaranteed to be the same as the order in which they were added to the object.

  • Object.keys() returns an empty array for null and undefined values.

  • Object.keys() is not supported in < IE9.

Conclusion

Object.keys() is a useful and powerful method in JavaScript that can help you extract the property names of an object. Keep in mind the notes mentioned above when using Object.keys() in your code.