As an exercise, I am trying to write a function called getValue()
which takes two parameters, obj
and key
.
This is unrelated to getting an index of an object by its property.
The function should pass in the name of an object (obj
) and the name of an object property (key
), the return the value associated with that property. If there is no value (that is, the property does not exist in the object), getValue()
should return undefined. As long as the named property does exist, the function should return its associated value.
I wrote a function that works but only if the property is named key
. Which of course is not what I had in mind.
function getValue(obj, key) {
this.obj = {};
this.key = obj.key;
const val = function() {
return obj.key;
};
return val();
}
var theObject = {nokey: 'my_value'};
var output = getValue(theObject, 'nokey');
console.log(output);
// --> 'should return 'my_value' but
// but returns undefined