maya90
1
I can’t print keys from an array of objects…
I tried using what’s in this fiddle, but it’s not working… my array is structured differently… instead of actual keys it prints “0” or “1”…
[FONT=Courier New]
var members = [{
name: "stephen gupta",
points: 52
},{
name: "laura kowalski",
points: 67
},{
name: "John Rodriguez",
points: 33
}];
[/FONT]
what I did:
[FONT=Courier New]
for (var i = 0; i < members.length; i++) {
$('#theMembers').append(keys[i] + ' : ' + members[i].name + '<br>' +
keys[i] + ' : ' + members[i].points + '<br><br>' );
}
[/FONT]
I know it’s not right, but I can’t figure out how to print something like
[FONT=Courier New]<li>name: stephen guta<br>points: 52</li>[/FONT]
.... etc...
thank you…
maya90
2
this works…
[FONT=Courier New] for (var i = 0; i < players.length; i++) {
$('.array ul').append('<li>name: ' + members[i]['name'] + '<br>points: ' + members[i]['points'] + '</li>');
}[/FONT]
but how can I print the keys without hard-coding them?
thank you…
A useful way to do that is by using Object.keys to get the keys of an object:
members.forEach(function (member) {
var text = '',
memberInfo = Object.keys(member).map(function (key, i) {
return key + ': ' + member[key];
});
$('.array ul').append('<li>' + memberInfo.join('<br>') + '</li>');
});
But you must be aware of compatibility issues when using more advanced JavaScript feature such as that.
As a result, the following tends to be used to loop through the properties of an object:
var prop;
for (prop in obj) {
if (obj.hasOwnProperty(prop)) {
// do stuff with prop and obj[prop]
}
}
You can see both examples being used in the test code at http://jsfiddle.net/pmw57/MSzaL/
maya90
4
thank you so much, Paul!! I really appreciate your help…