0

i want to use a for in oop to get the value of all the properties but do not know how. The tutorial i am following gives this example of how i can do it, but i dont understand it.

for(var x in dog) { console.log(dog[x]); }

var nyc = {
    fullName: "New York City",
    mayor: "Michael Bloomberg",
    population: 8000000,
    boroughs: 5
};

// write a for-in loop to print the value of nyc's properties
6
  • i know with this code for(var x in dog) { console.log(dog[x]); } Commented Jul 14, 2013 at 12:12
  • 1
    What does your Javascript book say? Commented Jul 14, 2013 at 12:13
  • print the value of each property in nyc using for in loop Commented Jul 14, 2013 at 12:14
  • 1
    It says a lot more than that. You need to learn the language. Commented Jul 14, 2013 at 12:14
  • 1
    You have an example for..in that works on an object called dog. Your object is called nyc. If you copy that loop to where the "write a loop" comment is, what change do you think you need to make to it to work with your object? Commented Jul 14, 2013 at 12:17

4 Answers 4

5

I suggest you to use variable name that has some meaning instead of x and y like:

for(var property in object){
    console.log(object[property]);
}

for your object

for(var prop in nyc){
    console.log(nyc[prop]);
}

Updated for ES6+

for(let prop in nyc){
    console.log(nyc[prop]);
}
Sign up to request clarification or add additional context in comments.

Comments

3
for (var property in obj){
     console.log(property + ": " + obj[property]);
}

This should do the trick, what this does is loops through the "Properties" of the object and logs the values accordingly.

Comments

0

you are missing + before value.

the correct line Object.entries(obj).map(([key, value]) => key + ":" + value)

Comments

-1

A one-liner would be:

Object.entries(obj).map(([key, value]) => key + ":" value)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.