Accessing object properties three

// Write a function that takes an object with two properties and a string as arguments
// It should return the value of the property with key equal to the value of the string
obj, key

Test Cases:
myFunction({ continent: 'Asia', country: 'Japan'}, 'continent')
myFunction({ country: 'Sweden', continent: 'Europe'}, 'country')

How to solve it

We have already learnt that you can access object properties using the dot notation or the square bracket notation (see here). In the following example, we use both approaches in a scenario where we know that the key of the property we want to access is x: const obj = { x: 1 };
// output: 1
// output: 1

However, in the above challenge, the key of the requested property changes. Test case 1 expects the value of a property with key continent and test case 2 expects the value of a property with key country.

In this case we can make use of the fact that the square bracket notation accepts a string that is stored in another variable:

const key = 'x';
const obj = { x: 1 };
// output: 1

This is a practical way to dynamically access object properties and can be used to solve this challenge.