Object Lookups in JavaScript
Object lookups are a powerful and commonly used feature of JavaScript. They allow you to access data stored in an object using a string key. This is an incredibly useful tool and allows you to dynamically access information stored in an object, without having to write out the entire object each time. In this tutorial, we will look at the basics of object lookups, and how they can be used to access data stored in an object.
What are Objects and Object Lookups in JavaScript?
Objects in JavaScript are a collection of key/value pairs that store data. Each key must be unique and is used to access the corresponding value. An object lookup is the process of finding a value stored in an object using a key. This is often done using the dot notation, which uses the object name followed by a dot and the key to access the value.
Example of Object Lookup in JavaScript
Let’s look at an example of an object lookup in JavaScript. Suppose we have an object called person, which stores information about a person, such as their name, age, and job title. We can access the value of the name key using the following code:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
person.name // returns the value of the name key in the object
[/dm_code_snippet]
Now, suppose we want to access the value of the job title key. We can use the same syntax to access the value, which would look like this:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
person.jobTitle // returns the value of the jobTitle key in the object
[/dm_code_snippet]
Using Variables to Access Object Data
You can also use variables to access the data stored in an object. This is often done using the bracket notation, which uses the object name followed by brackets containing the variable name to access the value. For example, suppose we have a variable called key that stores the string “name”. We can access the value of the name key using the following code:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
person[key] // returns the value of the name key in the object
[/dm_code_snippet]
Conclusion
Object lookups are a powerful and commonly used feature of JavaScript. They allow you to access data stored in an object using a string key. This is an incredibly useful tool and allows you to dynamically access information stored in an object, without having to write out the entire object each time. You can also use variables to access object data, which is often done using the bracket notation.