How to use a for-in loop In Javascript
- 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. The properties of the object are obtained by using a for loop on the object.
- These properties are then checked with the object’s hasOwnProperty() method to make sure it is a direct property of the object and not an inherited one.
- Each property is then checked if they are equal to the value to be found. If the value matches, then the property is returned. This is the key to the value of the object.
Example: This example is the implementation of the above-explained approach.
function getKeyByValue(object, value) {
for (let prop in object) {
if (object.hasOwnProperty(prop)) {
if (object[prop] === value)
return prop;
}
}
}
const exampleObject = {
key1: 'Geeks',
key2: 100,
key3: 'Javascript'
};
ans = getKeyByValue(exampleObject, 100);
console.log(ans);
Output
key2
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