0

I have the following javascript enum:

// Rooms
var rooms = {
 1: 'First Room',
 2: 'Second Room',
 3: 'Third Room',
};

I can easily get the room description as follows:

// Get Room Description
var roomOne = 1;
var roomdesc = rooms[roomOne];

How about if I have the room description 'First Room' and I want to get the room number?

I tried:

// Get room number
var roomIndex = rooms.indexOf('First Room');
var roomNum = rooms[roomIndex];

But indexOf is undefined. How can I get the room number by room description?

Thanks

PS: Forgot to mention. I cannot change the rooms object. It is being used in other areas already! Also, I would like to do this without using prototype or jquery. Thanks.

Robert Smith
  • 779
  • 1
  • 10
  • 28

3 Answers3

2

Try this:

var rooms = {
    1: 'First Room',
    2: 'Second Room',
    3: 'Third Room',
};

function test(val){
 for (var key in rooms) {
   if(rooms.hasOwnProperty(key))
    if (rooms[key] == val) {
        alert("Key:"+key);
    }
 }
}
test('First Room');//Pass the value you want to search for
Zee
  • 8,420
  • 5
  • 36
  • 58
0

I would suggest you to use Array's for this purposes:

var rooms = ['First Room','Second Room','Third Room'];
// Get Room Description
var roomOne = 0;
var roomdesc = rooms[roomOne];
// Get room number
var roomIndex = rooms.indexOf('First Room');
var roomNum = rooms[roomIndex];

console.log( roomNum )

Not that Arrays are zero-first indexed.

antyrat
  • 27,479
  • 9
  • 75
  • 76
-3

Try this:

var test = {
    1: 'First Room',
    2: 'Second Room',
    3: 'Third Room',
};
function getKeyByValue (obj, value) {
    for( var prop in obj ) {
        if( obj.hasOwnProperty( prop ) ) {
             if( obj[ prop ] === value )
                 return prop;
        }
    }
}
console.log(getKeyByValue( test, "Second Room" ));  // logs 2
Frank Adrian
  • 1,214
  • 13
  • 24
  • Copying an answer from another question is not really constructive. – Rob Raisch May 26 '15 at 16:01
  • What is the purpose to copy-paste answers from [other questions](http://stackoverflow.com/questions/9907419/javascript-object-get-key-by-value) rather than writing your own or point to that answers? – antyrat May 26 '15 at 16:01
  • Thanks, but is there a simpler 2 or 3 line solution without using Object.prototype? – Robert Smith May 26 '15 at 16:03
  • Well you can simply write a for loop on the Object, check if it hasOwnProperty and return the value. (Updated answer) – Frank Adrian May 26 '15 at 16:09