Object.keys

Learn the most powerful and commonly used Object method, 'Object.keys'. We'll discover how it enables us to work with objects as if they were arrays and how we can then use array methods to work with object data.

Like arrays, JavaScript objects have several functions available to them. There’s one that is by far more useful than any of the others: Object.keys.

One way to loop through each of an object’s properties is to use a for-in loop. This will iterate through the properties and allow us to work with the object’s keys.

Press + to interact
const obj = {
val1: 'abc',
val2: 'def'
};
for(const key in obj) { // const works here, but not in normal for-loops
console.log(key, obj[key]);
}
// -> val1 abc
// -> val2 def

Object.keys allows us to do more. It takes in an object as a parameter and returns an array that contains the keys of the object.

Press + to interact
const obj = {
val1: 'abc',
val2: 'def'
};
const keys = Object.keys(obj);
console.log(keys); // -> ['val1', 'val2]

That’s really all there is to this function. ...