Reputation: 161
Below code from URL (http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_state_forin) returns "John Doe 25". How can I fetch the property names like "fname lname age"?
<!DOCTYPE html>
<html>
<body>
<p>Click the button to loop through the properties of an object.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[name] + " ";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
Upvotes: 1
Views: 649
Reputation: 2818
You can get an array of all of the object properties (aka keys!) using the keys
function:
Object.keys(person);
So to print out the list of key/value pairs you can do:
var person = { fname:"John", lname:"Doe", age:25 };
var personProps = Object.keys(person);
for(var i = 0; i < personProps.length; i++){
var key = personProps[i];
var value = person[key];
console.log(key + " : " + value);
}
Or you can loop around the object's properties directly as follows:
var person = { fname:"John", lname:"Doe", age:25 };
for (key in person) {
console.log(key + " : " + person[key]);
};
Output:
fname : John
name : Doe
age : 25
Upvotes: 1
Reputation: 33466
A for..in
loop already iterates over the keys of the object. You just change person[x]
to x
.
var button = document.getElementById('tryit');
var output = document.getElementById('demo');
var person = { fname: "John", lname: "Doe", age: 25 };
button.onclick = function() {
var text = "";
for (var x in person) {
text += x + " ";
}
output.innerHTML = text;
};
<p>Click the button to loop through the properties of an object.</p>
<button id="tryit">Try it</button>
<p id="demo"></p>
It's also common to use Object.keys
along with Array.prototype.forEach
to do the same thing, but without iterating over any inherited properties from the prototype
of the object.
var text = "";
Object.keys(person).forEach(function(x) {
text += x + " ";
});
Upvotes: 0
Reputation: 150
You see that loop:
for (x in person) {
text += person[name] + " ";
}
x will be the properties of the person object.
Upvotes: 0
Reputation: 31682
Use Object.keys(yourObj)
to get an array of keys. Like:
function myFunction() {
var person = {
fname: "John",
lname: "Doe",
age: 25
};
var text = "";
var x;
var keys = Object.keys(person);
for (x = 0; x < keys.length; x++) {
text += keys[x] + " ";
}
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
Upvotes: 0