Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App

How to get a key in a JavaScript object by its value ?

Last Updated : 13 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To get a key in a JavaScript object by its value means finding the key associated with a specific value in an object. Given an object with key-value pairs, you want to identify which key corresponds to a particular value, often for searching or data retrieval.

Get-a-key-in-a-JavaScript-object-by-its-value
How to get a key in a JavaScript object by its value?


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 Object.entries() and reduce() Method
  • Using Lodash _.findKey() Method
  • Using Object.values() and indexOf() Method

1. Using a for-in Loop

The for-in loop iterates over an object's enumerable properties. You can compare each property’s value with the target value. If a match is found, return the key; otherwise, continue the loop until all properties are checked.

Example: In this example The for loop iterates over all properties in the exampleObject. It checks if the current property's value matches 100. If true, it returns the corresponding key (key2).

JavaScript
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

2. Using the find() Method

The find() method can be used with Object.keys() to find a key by its value. First, convert the object’s keys into an array using Object.keys(). Then, use find() to locate the key whose value matches the target value, returning the key.

Note: This method was added to the ES6 specification and may not be supported on older browser versions.

Example: In this example this function uses Object.keys() to get all keys, then uses find() to locate the key whose value matches 'Geeks'. It returns the first matching key (key1).

JavaScript
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

3. Using Object.entries() and reduce() Method

The Object.entries() method converts an object into an array of key-value pairs. Using `reduce()`, you can iterate over these pairs to find the key with the matching value. If the value matches, return the key; otherwise, continue accumulating until found.

Example: This example is the function uses Object.entries() to get key-value pairs, then applies reduce() to collect all keys whose values match 'Geeks', returning an array with the matching keys (['key1']).

JavaScript
function getKeyByValue(obj, value) {     return Object.entries(obj)     .reduce((acc, [key, val]) => {         if (val === value) {             acc.push(key);         }         return acc;     }, []); }  const exampleObject = {     key1: 'Geeks',     key2: 100,     key3: 'Javascript' };  ans = getKeyByValue(exampleObject, 'Geeks'); console.log(ans); 

Output
[ 'key1' ]

4. Using Lodash _.findKey() Method

Lodash’s _.findKey() method searches an object and returns the first key whose value matches a given condition. Pass the object and a predicate function that checks the value; it returns the key when the condition is met.

Example: This example is the _.findKey() method from Lodash is used to find the key of an object (users) that matches the condition { salary: 10000, active: true }, returning 'seetu'.

JavaScript
// Requiring the lodash library  const _ = require("lodash");  // Original array  let users = {     'meetu': { 'salary': 36000, 'active': true },     'teetu': { 'salary': 40000, 'active': false },     'seetu': { 'salary': 10000, 'active': true } };  // Using the _.findKey() method // The `_.matches` iteratee shorthand let found_elem = _.findKey(users, {     'salary': 10000,     'active': true });  console.log(found_elem); 

Output:

seetu

5. Using Object.values() and indexOf() Method

In this method, we'll leverage the Object.values() method to extract all the values from the object and then use the indexOf() method to find the index of the target value in the array of values. Once we have the index, we can use it to retrieve the corresponding key from the array of keys returned by Object.keys().

Example: The getKeyByValue function finds and returns the key matching the value in an object, or null if not found.

JavaScript
function getKeyByValue(object, value) {     // Get array of object values     const values = Object.values(object);          // Find the index of the target value     const index = values.indexOf(value);          // If the value is found     if (index !== -1) {         // Get array of object keys         const keys = Object.keys(object);         // Return the key at the same index         return keys[index];     }     // If value is not found, return null or handle accordingly     return null; }   let obj = {     name: "Alice",     age: 25,     city: "London" };  // Get the key for the value "London" console.log(getKeyByValue(obj, "London")); 

Output
city 

S

sayantanm19
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-object

Similar Reads

    How to declare object with computed property name in JavaScript ?
    In this article, we learn how to declare an object with a computed property name. Before beginning this article, we have to know about the javascript objects. Computed Property Names: The ES6 computed property names feature allows us to compute an expression as a property name on an object. Javascri
    2 min read
    How to add and remove properties from objects in JavaScript ?
    We will try to understand how to add properties to an object and how to add or remove properties from an object in JavaScript.Before we go and see the addition and removal of properties from an object let us first understand the basics of an object in JavaScript.Object:An object in JavaScript is a c
    6 min read
    How to check if a value is object-like in JavaScript ?
    In JavaScript, objects are a collection of related data. It is also a container for name-value pairs. In JavaScript, we can check the type of value in many ways. Basically, we check if a value is object-like using typeof, instanceof, constructor, and Object.prototype.toString.call(k). All of the ope
    4 min read
    JavaScript - Convert Two-Dimensional Array Into an Object
    Here are the different methods to convert the two-dimensional array into an object in JavaScript.1. Using a for LoopThe simplest way to convert a two-dimensional array into an object is by iterating through the array using a for loop and assigning key-value pairs.JavaScriptconst a = [['name', 'Abhay
    2 min read
    How to get all the methods of an object using JavaScript?
    In this article, we will learn how to get all the methods of an object using JavaScript. In JavaScript, we can get all the methods of an object by iterating over each object and checking if its property value is a function. An HTML document contains some methods and the task is to get all methods of
    2 min read
    How to implement a filter() for Objects in JavaScript ?
    In this article, we will learn how to implement a filter() for Objects in JavaScript. In JavaScript, the filter() method is a built-in function for the array, not for the object. The filter() method outputs all the elements of an array that pass a specific test or satisfies a specific function. The
    3 min read
    How to add a property to a JavaScript object using a variable as the name?
    In JavaScript, you can dynamically add a property to an object using a variable as the name. This allows you to create flexible and dynamic objects based on runtime values, enhancing code reusability and adaptability. There are several methods that can be used to add a property to a JavaScript objec
    2 min read
    How to Create Dynamic Values and Objects in JavaScript?
    In JavaScript, you can choose dynamic values or variable names and object names and choose to edit the variable name in the future without accessing the array, Dynamic values and objects in JavaScript allow changing, accessing, or creating values and object properties at runtime for flexibility and
    3 min read
    JavaScript - Print Object by id in an Array of Objects
    Here are the various methods to print objects by id in an array of objects in JavaScript1. Using Array.filter() MethodThe Array.filter() method, creates a new array containing only the object with the specified ID. JavaScriptconst a = [ { id: 1, name: "Alia" }, { id: 2, name: "Dua" }, { id: 3, name:
    3 min read
    How to get the last item of JavaScript object ?
    In this article, we will learn how to get the last item of a Javascript object. Given a JavaScript object and the task is to get the last element of the JavaScript object. This can be done by the following methods: Using Object.keys() methodUsing for loopmethodApproach 1: Use Object.keys() method to
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences