Assigning 'key: value' Lodash Invert

Hi everyone,

I have (what I believe is) a general question arising from my attempt to implement the ‘invert’ method from the lodash project.

Before attempting the implementation suggested by the instructions, I tried a slightly different way myself, without using a separate variable to store the original value in.

If I follow the instructions, and first assign the original value to a newly created variable, and create the inverted key:value pair, the method works well:

    invert (obj) {
        const invertedObj = {};
        for (let key in obj) {
            originalValue = obj[key];
            invertedObj.originalValue = key;
        }
        return invertedObj;

However, as I mentioned, I first tried to assign the original key as the inverted value in a single line:

    invert (obj) {
        const invertedObj = {};
        for (let key in obj) {
            invertedObj.obj[key] = key;
        }
        return invertedObj;

If I run that, I get a TypeError:

I have been trying to understand why one works and the other doesn’t, but couldn’t figure it out. Could anyone enlighten me, please?

Thanks!

here:

invertedObj.obj[key] = key;

invertedObj.obj will try to access obj property of invertedObj, which gives undefined. And you can’t assign to undefined.

look at this example:

example = {
  'a': {
    'b': 'c'
  }
}
console.log(example.a['b']);

the last line mirrors invertedObj.obj[key], as you can see, in my example it does a lookup, your code is also attempted it, but the right keys do not exists, for which you get undefined, to which you can’t assign

by doing this step first:

originalValue = obj[key];

no lookup occurs here:

invertedObj.originalValue = key;

you just assign, which is why this works.

Thanks for the quick and detailed response!

Just to make sure I get you correctly - the difference lies in the type of activity I’m actually asking to
perform, right?

I want to perform an ‘assignment’.

However, in my original implementation, I’m actually attempting to do a lookup instead, ending in getting an ‘undefined’ since what I’m looking for isn’t there (the ‘obj’ key in ‘invertedObj’).

Just out of extra curiosity, is there a way to this in a single line, or is it necessary to to have the variable in between?

actually, you do both (assign and lookup), but the lookup goes first. Which results in undefined, and you can’t assign to undefined.

Again, if we simplify the example:

example = {
  'a': {
    'b': 'c'
  }
}
example.a['b'] = 'd';
console.log(example.a['b'])

we can see it in action. We lookup the value for b property, and then assign it a new value.

i don’t think you can do this in a single line, too many operations which have to be carried out

Got it.

Thanks again!