Lodash step 23 : invert()

Hi Guys,

I’ve moved onto step 23 in the lodash project. Code aside, I’m having trouble understanding the semantics of the nomenclature.

Step 23 has a bullet which says:

  • .invert() iterates through each key / value pair in the provided object and swaps the key and value.

This seemed straight forward enough and I think I believe I understand. I tried the project before moving onto step 24 to see if I could do it. I thought I completed what is being asked for in this method:

// step 23 - 26 .invert method
  	invert(obj){
      const invertedObject = Object.entries(obj).map(([key, value]) => ({value, key})); // source: https://stackoverflow.com/questions/36411566/how-to-transpose-a-javascript-object-into-a-key-value-array 
    return invertedObject 
    }//closes the invert method

But, it failed the node test/invert.js test (see 2- below):

$ node test/invert.js
_.invert() Tests:
1 - _.invert() is defined - Passed!
2 - Returns an object with all keys and values inverted - F
ailed: _.invert({originalKey: "originalValue"})["originalVa
lue"]) returned undefined instead of originalKey.
3 - Returns an object with all keys and values inverted - P
assed!
$

FYI: Out of curiosity, I converted the above method to a function and used JSfiddle to figure out what I did wrong. I learned that although the key/values were transposed, the results were stuffed into an array of three objects which isn’t in the instructions. Oh well. Moving onto step 24.

I got confused when I got to step 24 bullet 4:

  • Set the original object’s value at that key to be a key on our inverted object and set the value of that key to be the original object’s key.

What does that bullet mean? Is step 24 bullet 4 asking for the same thing step 23 did at the top of this post?

Should I assume that the data fed into the invert method looks like this:
var data = { firstName: 'John', lastName: 'Doe', email: 'john.doe@gmail.com' };
Should I assume that the return value should be a single object like this:
var data = {'John': firstName, 'Doe': lastName, 'john.doe@gmail.com': email};

Thank you for any insight

1 Like

I think this post may answer my question.
//PASTE
var object = { ‘a’: 1, ‘b’: 2, ‘c’: 1 };
should output: {1: ‘a’, 2: ‘b’ 1: ‘c’}
//END

Does that look right?

1 Like

Yes, now you’re getting it but just clarifying this

Should I assume that the data fed into the invert method looks like this:
var data = { firstName: 'John', lastName: 'Doe', email: 'john.doe@gmail.com' };
Should I assume that the return value should be a single object like this:
var data = {'John': firstName, 'Doe': lastName, 'john.doe@gmail.com': email};

when you pass that to the method it should return
{John: 'firstName', Doe: 'lastName', 'john.doe@gmail.com': 'email'}

perfect. thank you very much!

1 Like