List ALL the Properties!


#1



Why it printed out the property not the value?


var nyc = {
    fullName: "New York City",
    mayor: "Bill de Blasio",
    population: 8000000,
    boroughs: 5
};

// write a for-in loop to print the value of nyc's properties

var a = "fullName";
var b = "mayor";
var c = "population";
var d = "boroughs";

var nycPropertyValues = [nyc[a],nyc[b],nyc[c],nyc[d]];

for ( var nycPropertyValues in nyc) {
    console.log(nycPropertyValues);
    }


#2

yea, the for loop prints out the properties, what is the question? the for in loop will give you access to the properties:

for (x in nyc){
  console.log(x);
}

then you can use the properties to access the values:

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

#3

I used nyc[a] to get the value of fullName property in the array. Does it supposed to print out "New York City"? However it printed out "fullName".


#4

there are two things in play here, you made a array:

var a = "fullName";
var b = "mayor";
var c = "population";
var d = "boroughs";

var nycPropertyValues = [nyc[a],nyc[b],nyc[c],nyc[d]];

and the loop:

for ( var nycPropertyValues in nyc) {
    console.log(nycPropertyValues);
    }

the for in loop will assign properties of nyc to nycPropertyValues (you could name this anything lik, it), but because you called it nycPropertyValues, it will overwrite your array!

so what you see in the output (thanks to the for loop) of the nyc properties, defined here:

var nyc = {
    fullName: "New York City",
    mayor: "Bill de Blasio",
    population: 8000000,
    boroughs: 5
};

so your list has just become overwritten. You don't even need the list:

var nyc = {
    fullName: "New York City",
    mayor: "Bill de Blasio",
    population: 8000000,
    boroughs: 5
};
for (x in nyc){
   console.log(x);
}

confusing isn't it? the for in loop does so much for you


#5

I think I was trying to do the following.

var a = "fullName";
var b = "mayor";
var c = "population";
var d = "boroughs";

var nycPropertiesValues = [nyc[a],nyc[b],nyc[c],nyc[d]];

for ( var i=0; i < nycPropertiesValues.length; i++) {
console.log(nycPropertiesValues[i]);
}

I read your comment about "overwritten" several times and finally understand it. Thank you sooo much! :slight_smile:


#6

true, but then you could also do:

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

#7

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