0

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
davedub
  • 94
  • 1
  • 8
  • I looked but could not find an answer to this precise question before. Link? – davedub May 20 '18 at 23:23
  • I really don't see how the linked-to question & answer relates to creating a function that returns the value of a property from an object by passing in the name of the object and the name of the key. – davedub May 20 '18 at 23:28

1 Answers1

2

Since you're passed the object itself, just access the property with bracket notation:

function getValue(obj, key) {
  return obj[key];
}

var theObject = {nokey: 'my_value'};
console.log(getValue(theObject, 'nokey'));

var object2 = {foo: 'bar'};
console.log(getValue(object2, 'baz'));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320