user3731460 user3731460 - 4 months ago 6
Javascript Question

How to log to the console a list of a JavaScript object's keys

How do I

console.log
a list of the keys of an object (e.g. "
12342341
" in the code below)?

var data =
{
"12342341": {
"City": "Montgomery",
"State": "AL"
},
"23482342": {
"City": "New York",
"State": "NY"
}
}

console.log('City: ', data[12342341].City);

Answer

Use Object.keys() methods to retrieve the property name array and Array#map method for generating City property value array from it.

var data = {
  "12342341": {
    "City": "Montgomery",
    "State": "AL"
  },
  "23482342": {
    "City": "New York",
    "State": "NY"
  }
};

// get property name array
var arr = Object.keys(data);

// iterate over property name and
// generate `City` property value array
var names = arr.map(function(v) {
  return data[v].City
});

console.log(arr, names);

FYI : If you just want the property name array then avoid the Array#map part.

Comments