Accessing Object Properties with variables : dynamic method

Tell us what’s happening:
Hi guys , below is a challenge that has two possible methods that can be used to solve the challenge. I managed to get the challenge correct using the first method , however when I tried the second method I couldn’t pass the challenge .I am looking for assistance with this .The link to the challenge is https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables

  **Your code so far**

// Setup
var testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};

// Only change code below this line

var playerNumber = 16;       // Change this line
var player = testObj[playerNumber];   // Change this line
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36

Challenge: Accessing Object Properties with Variables

Link to the challenge:

What do you think would be the second method? I only see one natural approach.

Hi @JeremyLT i was referring to the method that was explained in the notes as an alternative to the one that i used in my solution.The explanation for the method is written as follows:

Another way you can use this concept is when the property’s name is collected dynamically during the program execution, as follows:

var someObj = {
  propName: "John"
};
function propPrefix(str) {
  var s = "prop";
  return s + str;
}
var someProp = propPrefix("Name");
console.log(someObj[someProp]);

someProp would have a value of the string propName , and the string John would be displayed in the console.

that’s an example on why you want to access properties with variables

1 Like

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