Lodash Invert Solution

I couldn’t solve the invert method question, so I’ve reviewed the provided solution on video. However, when I tested the code, the outcome wasn’t as expected.

Invert() Method Implementation according to Codecademy video:

invert (object){
  let newObject = {};
  for (let key in object){
    const originalValue = object[key]
    newObject = {originalValue: key}
  }
  return newObject;
}

And here is how I tested:

var obj1 = { 'a': 1, 'b': 2, 'c': 1 };
console.log(_.invert(obj1));

It returned {originalValue: ‘c’ }, instead my expectation was seeing the following to be returned: { ‘1’: ‘c’, ‘2’: ‘b’ }

Can someone help if I’m missing something on the logic here?

You used that as the key, no mystery there.

I used ‘b’ as a key too, but it’s not in the output. Why might that be?

not in the code you posted here you didn’t

Sorry maybe I’ve been looking at the screen for so long, but aren’t ‘a’, ‘b’, and ‘c’ the keys here?

Are you sure you didn’t just type something and hope it would be right?

What action do you mean to carry out, and what does that action look like in code?

You are doing some operation that isn’t having the desired result. Right? Which operation is that? Can you print out what you have before and what you have after to observe that some single operation isn’t having your desired outcome?

And then you’d ask yourself, hey, what action is this supposed to be, and what does that look like (you’d google it, or look it up directly if you know where to find it… but you’d probably google anyway because that’s like an index of documentation)

So, presumably the operation you are looking for is:
given a key and a value, add that key-value pair to the object.

You have this:

obj = {}
key = 'a'
value = 'b'

And you want:

{'a': 'b'}

What does that operation look like in code? Is there some documentation you can use that explains how to do that? (Probably among the first things you learn about objects - how to get and set properties)

You could make your code write out this information to trace what is being done:

newObject: {}
current key/val from original: a 1
newObject: { '1': 'a' }
current key/val from original: b 2
newObject: { '1': 'a', '2': 'b' }
current key/val from original: c 1
newObject: { '1': 'c', '2': 'b' }

That would tell you whether the loop has the right information, and whether the object is being changed correctly at each step, and if not, how it is changed differently from what you meant.

I have been playing around with newObject variable to return above results. All I could get was
{originalValue: '1', key: 'c'} as result… So it still doesn’t accumulate the others that should be brought ( ‘2’ : ‘b’ } and I can’t figure out eliminating the key name from the result (originalValue and key).

invert (object){
  let newObject = {};
  for (let key in object){
    const originalValue = object[key]
    newObject = {originalValue: originalValue, key: key}
  }
  return newObject;
},

The code in that video is horrifically wrong. As you noticed.

The operation you are looking for is: set a property on an object
That operation is like… the second thing you learn about objects! Right? So after narrowing it down to being that operation being done wrong, you can then look up how this operation is carried out and then fix it.

Try not to pay too much attention to the text in the code. What matters is the actions, deciding what should happen is how you can know what you need to look up if you don’t already know how it’s done.

And when reading code, same thing there. Consider what action each thing is. If any syntax is unfamiliar… gotta look it up, no way around it.

1 Like

Thanks I’ll play around with a setter.

Below also solved the issue.

invert (object){
let newObject = {};
for (let key in object){
const originalValue = object[key];
 newObject[originalValue] = key; 
}
return newObject;
}
1 Like

Thanks for the solution…I was stuck at here too when i tested out the video steps with a created object.
Not sure why the {originalValue :key} works in the node test/invert.js test but not when its tested separately as a function/method call…

@microplayer64661

I can’t comment on this solution video as I’m currently working on this project and yet to watch it, but I have been disappointed by more than one solution video before.

I struggled with .invert(), too. Here’s what got me over the line:

invert (obj) {
  // Target object placeholder
  newObj = {};
  // Loop iterating through object keys
  for (key in obj) {
    // Create new key from currently iterated value and set currently iterated key as its value
    newObj[obj[key]] = key;
  }
  // Return the complete object after iteration finishes
  return newObj
},

Regarding your original question, it seems to me that each time your loop iterates, you may be overwriting your object rather than building on it. You don’t want a new object on each iteration, but a new key/value pair. My example above with your variable names might look like:

newObj[originalValue] = key;

I really hope this helps in some way. I am a beginner at this and I’m always happy to be proven wrong. :upside_down_face:

1 Like

I’m working on this exercise right now, and am very confused by the implementation instructions (and the video) which, to me, don’t seem to accurately express the object of the exercise.

Here’s my code, which I know is completely wrong (keeps throwing syntax errors), but this makes sense to me. I wish I could figure out how to observe and test my code, but when I do, I just get more syntax errors in the console…I’m still trying to figure out how the whole console debugging thing works

 // .invert() iterates through key:value pairs of an object and swaps (inverts) keys and values, and then returns a new object 
  invert (object) {
    let newObj = {};
//console.log('newObj is ' + newObj); output: undefined (yay, something worked!)
   for ([key,value] in object) {
//console.log('before key & value are ' key + object); output: Uncaught SyntaxError: missing ) after argument list
    let temp = key;
    let key = value; // key is undefined!!! this won't work
    let value = key;
//need a function or this won't work, right? what do I want this to do? I need it to swap values, but didn't I express that with the above variables (two of which are undefined, right)? Hmmmm.
//console.log('after key & value are ' key + object); output: Uncaught SyntaxError: Unexpected token '{'
    };, output: Uncaught SyntaxError: Unexpected end of input
    return newObj{ key : value};
//console.log(newObj); output: illegal return statement
  } 

I don’t understand how your (@cakaragiannis) code, written how it is, inverts the keys and values from the original object. Can you / someone explain?

(sidenote: Could someone please explain to me like I’m a 3-year-old how to use the console to test code? I’m forever stuck and lost when I try to ‘test’ my code using the chrome web dev tools console debugger.

** Since I’ve been using Codecademy the console throws syntax or reference errors when I try to do it.*
** I don’t know if I’m placing the console.log code in the right place, or if I’m console.logging the right things or what // and I’m sorry but I know this sounds really stupid…believe me, that’s how I feel – but for whatever reason, I’m lousy at it. *
** Is there a really basic, beginner-level lesson on how to use the console to debug JS code using layman’s terminology that someone can share?*)

Example object:

let person = {
  name: "Chris",
  age: 34,
}

Let’s add one more property:

person.hobbies = "coding and guitar"

We can do the same thing with:

person["hobbies"] = "coding and guitar" 
//We'll be using this syntax to handle problem strings 
// e.g. like "coding and guitar". 'newObj."coding and guitar' = " simply won't do.

Now we have:

let person = {
  name: "Chris",
  age: 34,
  hobbies: "coding and guitar"
}
  • A new object variable ‘newObj’ is created;
  • A for…in loop will iterate over the properties of the ‘person’ object;
  • The first loop iterates over the “name” property;
  • Thus the variable ‘key’ = “name” on this iteration…

We want to assign newObj a new property on each iteration. We do this as with adding hobbies. i.e.:

newObj["propertyKey"] = propertyValue
// where 'propertyKey' should evaluate to "Chris" and propertyValue should evaluate to "name" on this iteration...

Let’s replace ‘propertyKey’ with code that evaluates to “Chris”. person[name] returns “Chris”:

newObj[ obj[ key ] ]
// i.e. newObj[ person[ "name" ] ]

…and replace ‘propertyValue’ with code that evaluates to “name”. We already established that ‘key’ evaluates to “name” on this iteration of our loop.

= key
// i.e. = "name"

Putting it all together, we get:

newObj[ obj[ key ] ] = key
// i.e. newObj[ person[ name ] ] = "name"
// i.e. newObj[ "Chris" ] = "name"
1 Like

console.log for beginners

1 Like

My solution was exactly like yours, but I did it by accident. I think the problem @bobbieganujsh was having was identical to mine–getting a new property of an object declaration mixed up with changing the value of a normal variable.

invertedObject[objectVar[prop]] = prop;

feels/looks like

x = 25;

but x = 25 is just changing the value of an already declared variable (let x = 20, for example), whereas the other statement creates both the property name and the value in the single statement, because that’s how it works for objects.

2 Likes

For whatever reason I have the hardest time with this – I tend to console.log the wrong things or use it in the wrong way, so THANKS so much for posting this tutorial.

1 Like

No problem, we all have our coding kryptonite!

1 Like