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!

3

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

3

You should try this way object[key]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.