LODASH findKey() question

Hi,

I came up with this before looking at ideate/implement:

findKey (object, predFunc) {
  
  for(let key in object){
    let value = predFunc(object[key]);
    return value ? key : undefined;
    }
  }
}

was wondering if there’s any benefit to adding an additional variable as the instructions do:

  1. Within the loop, create a variable called value and set it equal to the value at the current key in object .
  2. Still within the loop, create another variable called predicateReturnValue and set it equal to the result of calling >predicate with value .
  3. Finally, still within the loop, use an if statement to check to see if predicateReturnValue is truthy. If it is, return the > current key from the method.
  4. Outside of the loop, return undefined to address all cases where no truthy values were returned from predicate.

My tests all pass, but that’s not necessarily indicative of better/more efficient code.

Hello,

There really isn’t an efficiency benefit to assigning it to another variable if you won’t need to use it again. In some situations, I could see it being useful to make it clearer what the code is doing with descriptive variable names though.

I’m going to take this as almost a request for feedback on the code you posted. Your code passes the tests in the project, but it doesn’t handle all the use cases that it’s supposed to cover. That’s more the fault of them not including enough tests to handle very common uses of the method.

If you run the following code:

// lifted this predicate function directly from their test
const startsWithV = string => string.startsWith('v');

const testObject1 = {key: 'value'};
const testObject2 = {key: 'nope', second: 'value'};
const testObject3 = {key: 'testing'};

console.log(_.findKey(testObject1, startsWithV));
console.log(_.findKey(testObject2, startsWithV));
console.log(_.findKey(testObject3, startsWithV));

You should see:

key
second
undefined

but instead you’ll currently see:

key
undefined
undefined

I haven’t mentioned what’s wrong with your method so you can figure out what’s going on and get experience with fixing it, but I’ll mention more in the hint below.

Edit: Notice that in the sample above, I assigned the objects to variables only for the sake of clarity. In this case, I wanted you to be able to see their values and easily compare them without having the other code from the method calls and console logs.

Click for another hint

You’re only checking the first key because your method returns undefined if the first call to the predicate function isn’t true. The others never have a chance to be checked.

1 Like

My question is more broad. Where should one look to find how to iterate over a nested object? It is clear to me that I do not. My obj[key] returns [object object]. Really tired of objects right about now. Getting ready to findKey hardcoding just to get past this exercise