Sling Academy
Home/JavaScript/JavaScript: Get the Key of an Object Property by Its Value

JavaScript: Get the Key of an Object Property by Its Value

Last updated: March 14, 2023

When developing websites and applications with JavaScript, there might be times when you need to retrieve the key of an object property by its value. This task can be done in several different ways. Let’s explore them, one by one, in this concise example-based article.

Using the Object.keys() and find() methods

You can use the Object.keys() method to get an array of keys and then use the Array.prototype.find() method to find the key that matches the value.

Example:

const myObject = {
    name: 'Sling Academy',
    age: 10
}

const value = 'Sling Academy';

// Find the key of the object that has the value 'Sling Academy'
const result = Object.keys(myObject).find(key => myObject[key] === value);

// Print the result
if(result){
    console.log(result); 
} else {
    console.log('Key not found');
}

Output:

name

This approach is quick and elegant. The main logic only requires a single line of code.

Using a for…in loop

You can also use a for…in loop to iterate over the object’s properties and compare them with the given value.

Example:

// define a reusable function
const getKeyByValue1 = (object, value) => {
  for (var key in object) {
    if (object.hasOwnProperty(key) && object[key] === value) {
      return key;
    }
  }
};

// try it out
const obj = { a: 1, b: 2, c: 3 };
console.log(getKeyByValue1(obj, 2)); 

Output:

b

Using the Object.entries() and reduce() methods

This solution converts the object to an array of [key, value] pairs using Object.entries() and reduces the array to the first key that has the target value.

Example:

// define a reusable function
const getKeyByValue = (object, value) => {
  return Object.entries(object).reduce(
    (acc, [key, val]) => (val === value ? key : acc),
    null
  );
};

// Example usage
const obj = {'slingAcademy': 1, 'blue': 2, 'green': 3}
const value = 1;
console.log(getKeyByValue(obj, value)); 

Output:

slingAcademy

Afterword

We’ve walked through a couple of different ways to find an object key by a provided value in modern JavaScript (arrow functions, new built-in methods). None of them is verbose or longer than necessary. Pick the one you like to go with.

If you find errors or anachronisms in the code examples, please let us know by leaving comments. We will review and update them as soon as possible.

Next Article: JavaScript: Create/Access Object Properties with Variable Keys

Previous Article: JavaScript: 3 Ways to Remove a Property from an Object

Series: Working with Objects in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration