0

In the code below, how would I return the names of the properties (prop1, prop2, prop3) of the object, myObject?

var myObject = {
    prop1: "lorem",
    prop2: "ipsum",
    prop3: "dolor"
};

for (var key in myObject) {
    console.log(???);
}
Uncle Slug
  • 853
  • 1
  • 13
  • 26

5 Answers5

3
for (var key in object) {
    console.log(key);
}

Edit: I'd just like to mention it's best practice to use hasOwnProperty to check whether or not the object has the property because otherwise you will iterate over the entire prototype chain.

Lauren
  • 56
  • 2
1

An alternative is to use the keys method to get them into an array:

var keys = Object.keys(myObject);

And then you can just iterate over the array with a normal loop. This is often useful if you want to perform multiple operations on the object keys.

Andy
  • 61,948
  • 13
  • 68
  • 95
1

You need to use myObject instead of object:

var myObject = {
    prop1: "lorem",
    prop2: "ipsum",
    prop3: "dolor"
};
for (var key in myObject) {
  console.log("key:", key, "value:", myObject[key])
}
Chavdar Slavov
  • 865
  • 8
  • 22
1

You can iterate them with Object.keys()

Object.keys(myObject).map(function(key) {
  console.log(key);
});
M. Adam Kendall
  • 1,202
  • 9
  • 8
  • This is kind of a long-winded way to go about what can be achieved with a simple loop, as demonstrated by Lauren. – Andy Apr 09 '15 at 00:20
0

var key <--- key contains the names of the properties

Erick
  • 823
  • 16
  • 37