How to use the find Method() In Javascript
- The Object.keys() method is used to return all the keys of the object.
- On this array of keys, the find() method is used to test if any of these keys match the value provided.
- The find() method is used to return the value of the first element that satisfies the testing function.
- If the value matches, then this condition is satisfied and the respective key is returned. This is the key to the value of the object.
Note: This method was added to the ES6 specification and may not be supported on older browser versions.
Example: This example is the implementation of the above-explained approach.
function getKeyByValue(object, value) {
return Object.keys(object).find(key =>
object[key] === value);
}
const exampleObject = {
key1: 'Geeks',
key2: 100,
key3: 'Javascript'
};
ans = getKeyByValue(exampleObject, 'Geeks');
console.log(ans);
Output
key1
How to get a key in a JavaScript object by its value ?
In this article, we will learn how to get a key in a JavaScript object by its value. The values of the object can be found by iterating through its properties. Each of these properties can be checked to see if they match the value provided.
Below are the approaches through which we get a key in a JavaScript object by its value:
Table of Content
- Using a for-in loop
- Using the find Method()
- Using filter() Method and Object keys() Method
- Using Object.entries() and reduce() Method
- Using Lodash _.findKey() Method
- Using Object.values() and indexOf() Method