get the key in javascript

To get the keys (property names) of an object using JavaScript, you can use the built-in Object.keys() method. This method accepts an object as its argument and returns an array of the object's keys.

Here's an example:

index.tsx
const myObject = { 
  name: 'John', 
  age: 30, 
  city: 'New York'
}; 

const keys = Object.keys(myObject);

console.log(keys); // Output: ["name", "age", "city"]
164 chars
10 lines

The Object.keys() method is useful for iterating over an object's properties in a loop. For example:

index.tsx
const myObject = { 
  name: 'John', 
  age: 30, 
  city: 'New York'
}; 

for (const key of Object.keys(myObject)) {
  console.log(key + ': ' + myObject[key]);
}
// Output:
// name: John
// age: 30
// city: New York
215 chars
14 lines

In this example, Object.keys() returns an array of the keys in myObject. The for...of loop iterates over each key in the array, and the myObject[key] syntax is used to access the value of the property with the current key.

gistlibby LogSnag