Problem Statement
What does Object.keys() return?
Explanation
Object keys returns an array containing all enumerable property names of an object.
It only returns own properties, not inherited ones.
The order matches the order in which properties were added.
This is useful for iterating over object properties or checking if an object has any properties.
Combine with map or forEach to process object properties.
Code Solution
SolutionRead Only
const person = {
name: 'John',
age: 30,
city: 'New York'
};
// Get all keys
const keys = Object.keys(person);
console.log(keys); // ['name', 'age', 'city']
// Check if object is empty
const isEmpty = Object.keys(person).length === 0;
console.log(isEmpty); // false
// Iterate over keys
Object.keys(person).forEach(key => {
console.log(key, person[key]);
});
// Get values
const values = Object.values(person);
console.log(values); // ['John', 30, 'New York']
// Get key-value pairs
const entries = Object.entries(person);
console.log(entries);
// [['name', 'John'], ['age', 30], ['city', 'New York']]
// Convert back to object
const obj = Object.fromEntries(entries);
console.log(obj); // {name: 'John', age: 30, city: 'New York'}