❝ O Romeo, Romeo! wherefore art thou Romeo?
Deny thy father and refuse thy name;
Or, if thou wilt not, be but sworn my love,
And I'll no longer be a Capulet. ❞
Working with Objects in Javascript
Each time I feel I've got a handle on one concept, low and behold, something new is presented. Luckily, it's done in such a way that builds on previous challenges. This challenge introduced associative arrays, which is an an abstract data type made of a collection of key:value
pairs. Keys are sometimes referred to as name, or in other languages, a hash.
It's been said that everything in Javascript is an object, which is true... kinda.
Values such as Booleans Numbers Strings Undefined
and Null
(the latter we will not go over now) are primitive values and represent the most simple forms of data we can use in JS programming - in other words - not objects.
But what you will find is sometimes they are. That is the beauty of a loosely typed language like Javascript. But, bececause the language is so forgiving, you, dear programmer, may find yourself in trouble.
Below, we are to create a function that takes in two arguments and iterates through an array of objects (first argument) and returns an array with matching properties and values pairs of the second argument. The property and value of the source
object must be present in the collection
object in order to be included in the returned array.
Given these variables:
The third object from the collection argument [{last: "Capulet"}]
should be returned as a new Array as it has the that property-value pair as the second argument.
This function introduced me to some new awesome methods:
obj.hasOwnProperty
Returns a boolean (true, false)
depending on whether the object has the specified property.
Object.keys(obj)
Returns an new array composed of the Object’s enumerable properties in the same order as a for…in
loop would, without checking down the prototype chain.
How this differs from the in
operator is this method does not do a check through the object's prototype chain. Using these two methods, along with filter()
and every()
I was able to successfully compose the function:
I hope this succinctly explains what is going on with the above function. The most challenging part for me with using higher order functions is syntax; knowing when and where to chain functions together to get the appropriate solution.