Association Methods in Javascript
Objectives
Learn how to build methods to select associated objects.
Learn how to build methods to find objects by certain attributes.
Associating Objects
In the previous lesson we saw how to associate objects through use of a store and adding functionality to our JavaScript classes. Let's take another look at that code.
Now the next thing we need to do is build some methods that would select the associated data. For example, if we want to find all of the items associated with the first user, we would like to write a method called items()
that would retrieve all of the items associated with the first user:
Ok, now how would we implement a method on our user object that finds the associated items? Well, the way we can identify the items associated with the first user is go to our store, and go through each of the items in our store
and return the ones with a userId
equal to 1. We can use JavaScript's filter
method to do just that. Let's go for it!
So you can see that the code above uses the filter
method to go through the items in the store
and return each of the items that have a userId
equal to the id of the user receiving the items method call. Ok, that was the hard one, now let's write a method item.user()
such that the user associated with the item is returned.
Unlike our use of the filter
method, JavaScript's find
method only returns the first matching element from the array. With our items()
added to our user objects and the user()
method added to our item objects we have set up our relationship in both directions.
Summary
In this lesson, we saw how to write methods to select our associated data. We saw that by using JavaScript's filter
and find
methods we can search the store
to return the proper JavaScript objects when our methods are called.
Resources
Last updated