javascript getProperty

24.1k views Asked by At

I'm a complete beginner trying to learn Javascript. I am trying to complete a problem requiring me to return a value assigned to a key. The function is called getProperty and I am stuck - it keeps returning "should return the value of the property located in the object at the passed in key" every time I attempt to run a test on the code.

    var obj = {key: 'value'};

    function getProperty(obj, key) {
        var o = obj.key;
        return(o);
    }

    console.log(getProperty);
2

There are 2 answers

1
Rob M. On

For dynamic attribute names you need to use the bracket [] notation instead of the dot notation:

var o = obj[key];
return o

Thanks to @Gaby for pointing out that you also need to call the function with valid arguments:

console.log(getProperty(obj, 'key'));
0
Abbas Reza On

The "key" parameter for the method is irrelevant since you are not using it anywhere in the method. Also, the method needs the obj parameter when you call it.

   var obj = {key: 'value'};

    function getProperty(obj) {
        var o = obj.key;
        return(o);
    }

    console.log(getProperty(obj));