Week 4 Loops - for in and if statement - question

javascript
#1

Hi All

I’m really happy to know that we have our own forum now!

I’m stuck trying to create an if statement inside a “for in” loop using object keys.

Here’s the question:
// for…in loop
// Create an object (an array with keys and values) called persons with the following data:
// firstName: “Jane”
// lastName: “Doe”
// birthDate: “Jan 5, 1925”
// gender: “female”
// Use a for…in loop to console.log each key.
// Then use a for…in loop and if state to console.log the value associated with the key birthDate.
// while loop

Here’s the code:

const persons = {
  firstName: "Jane",
  lastName: "Doe",
  birthDate: "Jan 5, 1925",
  gender: "female"
};

for (const i in persons) {
  console.log(persons[i]);
}

for (const i in persons) {
  if (i === persons[birthDate]) {  // using an if statement to compare keys from object (this is where I need help)
    console.log(`${i} --> ${persons[i]}`);
  }
}

Using an if in statement to compare keys from object - any help is greatly appreciated!

1 Like
#2

so a for in loop the variable you set is the string that represents the key

so

for (const i in persons) {
  console.log(i) // i === EACH KEY in the object
}
  // firstName
  // lastName
  // birthDate
  // gender

So if you just want the key name

console.log(i)

if you want the value use bracket notation on the object

console.log(persons[i]) // i will be replaced with the current key in the key: value pair

so in your if statement it needs to be

for (const i in persons) {
  if (i === 'birthDate') { 

since i === the string form of the key

    console.log(persons[i]); 

which is the same as persons.birthDate since i === birthDate in this if block

FULL CODE BELOW:

const persons = {
  firstName: "Jane",
  lastName: "Doe",
  birthDate: "Jan 5, 1925",
  gender: "female"
};

for (const i in persons) {
  console.log(i]);
}

for (const i in persons) {
  if (i === "birthDate") { 
    console.log(persons[i]);
  }
}
2 Likes
#3

Thanks Tosin!

I see the notation for ‘birthdate’ is where the main problem was.