Preethi Jain Preethi Jain - 4 months ago 14
Javascript Question

Is it possible to extract only the key part while looping?

I have got the above key value pair structure

While looping is it possible to extract only the key

var list_of_stocks= {
"CBB": "Communications",
"VZ": "Communications",
"UPS": "Transportation"
};
for (var key in list_of_stocks) {
console.log(list_of_stocks[0]);
}


So that the output will look like

CBB
VZ
UPS


http://jsfiddle.net/n3fmw1mw/207/

Answer

Just log key:

var list_of_stocks= {
      "CBB": "Communications",
      "VZ": "Communications",
      "UPS": "Transportation",
      "RRTS": "Transportation",
      "AAC": "Heath"
};
for (var key in list_of_stocks) {
  console.log(key);
}

Want an array of keys? Use Object.keys():

var list_of_stocks= {
  "CBB": "Communications",
  "VZ": "Communications",
  "UPS": "Transportation",
  "RRTS": "Transportation",
  "AAC": "Heath"
};

var keys = Object.keys(list_of_stocks);

console.log(keys);
console.log(keys[0]); //CBB