- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get key from value in JavaScript
Suppose, we have an object of arrays like this −
const obj = { 'key1': ['value11', 'value12', 'value13', 'value14', 'value15'], 'key2': ['value21', 'value22', 'value23', 'value24', 'value25', 'value26', 'value27'], 'key3': ['value31', 'value32', 'value33', 'value34'], 'key4': ['value41', 'value42'], };
We are required to write a JavaScript function that takes in one such object as the first argument and a value string as the second argument. The function then should check to which key the input value belongs.
for 'value13', the key will be 'key1' for 'value32', the key will be 'key3'
Example
The code for this will be −
const obj = { 'key1': ['value11', 'value12', 'value13', 'value14', 'value15'], 'key2': ['value21', 'value22', 'value23', 'value24', 'value25', 'value26', 'value27'], 'key3': ['value31', 'value32', 'value33', 'value34'], 'key4': ['value41', 'value42'], }; const searchByValue = (obj, val) => { for (let key in obj) { if (obj[key].indexOf(val) !== -1) { return key; }; }; return null; }; console.log(searchByValue(obj, 'value32'));
Output
And the output in the console will be −
key3
- Related Articles
- Get value for key from nested JSON object in JavaScript
- Get key from value in Dictionary in Python
- Get max value per key in a JavaScript array
- Extract key value from a nested object in JavaScript?
- Java Program to Get key from HashMap using the value
- How to Get Value from HashTable Collection in C# using Specified Key
- JavaScript: How to Create an Object from Key-Value Pairs
- How to get a key/value data set from a HTML form?
- Get lower key from NavigableMap in Java
- Get first key from NavigableMap in Java
- Get last key from NavigableMap in Java
- Get ceiling key from NavigableMap in Java
- Get higher key from NavigableMap in Java
- Get floor key from NavigableMap in Java
- Get key with maximum value in Dictionary in Python

Advertisements