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(???);
}
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(???);
}
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.
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.
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])
}
You can iterate them with Object.keys()
Object.keys(myObject).map(function(key) {
console.log(key);
});