Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Issue changing strings in Objects using for in loop!

I'm looking at changing the value of each key in the Object to "I've been changed!". So far I've used a 'for in' loop to cycle through the object but I'm not sure how to change the values.

How would I do this?

Here's the code!

// Create your own object with five key-value pairs.
// Loop over it and change each value to "I've been changed!"
// Console log the final object with its changed values.

var personObj = {
    name:"Matt",
    age:25,
    pet:true,
    food:"Brisket",
    location:"Manchester"

}

for (var attr in personObj){
    console.log(attr + personObj[attr] = )


}

2 Answers

This doesn't work:

    console.log(attr + personObj[attr] = "I've been changed")

because when you add two strings, the strings must alrady have a value, you can't be like add these two strings with the second string equal to "I've been changed". It wants the second string to already have the value which you want to add to the first one. Think of math, you can't say: f(x) = 1 + (x = 2) . You can say x = 2; f(x) = 1 + x.

This would work:

    console.log(personObj[attr] = "I've been changed")

it assigns the value to personObj[attr] and then passes it as an argument to the console.log() function, but this isn't what you want, because you also want to print the attribute, so you need a different solution.

So if you want to print out both attribute and value you will need to first assign the value and then print it, like so:

for (var attr in personObj){
    personObj[attr] = "I've been changed!"

    console.log(attr + personObj[attr] )
}

Thanks! Makes a lot more sense now. I should stop tackling problems when I'm exhausted, it only makes more hard work.