Lodash has() why does my code not work?

Can someone tell me why this code does not pass the has() method test in the Lodash project? it will pass the first two tests, declaring the method properly and returning true but it will not pass the third test of returning false.

has (obj, key) {
    let hasValue = obj.key !== undefined ? true : false; 
    return hasValue;

  },

This is the error code I get:

3 - Returns false if an object does not have a value at a specified key - Failed: _.has({“key”: “value”}, “notKey”) returned true instead of false.

It has to do with how you’re writing obj.key.

obj[key]

Explanation

What’s happening is that your method is looking for a property of key in your obj, so you want to search it dynamically by passing in whatever property is there.

Great example here:
Difference between object.key and object[key] in for loop in JavaScript - Stack Overflow

  • obj.key equal obj["key"] will look for "key" as a property in your object, and obviously there is no key property in animals object ==> obj.key equal obj["key"] is undefined . ==> you got unexpected result.
  • obj[key] is dynamically take the value of key to pass in the notation. E.g const key = "name" => obj[key] equal obj.name . It is "bird" in your case obj[key] equal obj["bird"] equal obj.bird

Thank you @keegankwirant8521787 this is a great explanation!

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.