1

Trying to access integer stored under id's/keys in json object. Why doesn't this code work on its own?

 var rooms = {
    'kitchen': [7, 40, 36, 16],
    'livingroom': 31,
    'livingroom2': 15,
    'livingroom3': 38,
    'gallery': 35,
    'gallery2': 29,
    'gallery3': 12,
    'office': [22, 32],
    'neekonsbedroom': 18,
    'homeworkroom': 33,
    'diningroom': 13,
    'atrium': 11
}
function switchOne(id) {
    console.log(rooms.id)
}
 switchOne('office')

console.log() returns undefined, but simply console.log(rooms.office) returns [ 22, 32 ] Any and all help is greatly appreciated! Happy coding!

Neekon Saadat
  • 417
  • 6
  • 18
  • 5
    rooms[id] ..... – Ivan Ivanov Nov 15 '17 at 07:09
  • 3
    Possible duplicate of [JavaScript object: access variable property by name as string](https://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-by-name-as-string) – Ivan Ivanov Nov 15 '17 at 09:20
  • 1
    Possible duplicate of [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – Mark Ormesher Nov 16 '17 at 08:36

2 Answers2

6

You're looking for the literal key "id" within your object, not the key at the value of id (i.e. "office"). To get Javascript to treat id as a variable you need to use rooms[id].

The information here explains (towards the bottom) accessing properties of objects: https://www.w3schools.com/js/js_object_definition.asp.

Mark Ormesher
  • 2,289
  • 3
  • 27
  • 35
3

You should try this way object[key]

mohsin
  • 594
  • 2
  • 8
  • 29