Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing all properties in a Javascript Object [duplicate]

Tags:

javascript

I am following a code academy tutorial and i am finding this difficult.

The assignment is the following:

Use a for-in loop to print out all the properties of nyc.

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

// write your for-in loop here
for (var  in nyc){
    console.log(population);
}
like image 959
Rtr Rtr Avatar asked Jul 13 '13 07:07

Rtr Rtr


People also ask

How do I print all properties of an object?

First way to print all properties of person object is by using Object. keys() method. In this method we pass the person object to Object. keys() as an argument.

How do you copy properties from one object to another in JavaScript?

Using Object. The Object. assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.


2 Answers

Your syntax is incorrect. The var keyword in your for loop must be followed by a variable name, in this case its propName

var propValue;
for(var propName in nyc) {
    propValue = nyc[propName]

    console.log(propName,propValue);
}

I suggest you have a look here for some basics:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

like image 107
lostsource Avatar answered Oct 11 '22 13:10

lostsource


What about this:

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

for (var x in nyc){
    txt += nyc[x];
}
like image 10
Tomas Nekvinda Avatar answered Oct 11 '22 13:10

Tomas Nekvinda