Introduction
In this lab, we will explore how to find all the keys in a JavaScript object that match a given value. By using Object.keys() and Array.prototype.filter(), we can efficiently search through an object and return an array of keys that correspond to the provided value. This will be a valuable skill for any JavaScript developer working with complex data structures.
Find Matching Keys
To find all the keys in an object that match a given value, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Object.keys()to get all the properties of the object. - Use
Array.prototype.filter()to test each key-value pair and return all keys that are equal to the given value.
Here's an example function that implements this logic:
const findKeys = (obj, val) =>
Object.keys(obj).filter((key) => obj[key] === val);
You can use this function like this:
const ages = {
Leo: 20,
Zoey: 21,
Jane: 20
};
findKeys(ages, 20); // [ 'Leo', 'Jane' ]
Summary
Congratulations! You have completed the Find Matching Keys lab. You can practice more labs in LabEx to improve your skills.