Jump to content

Json Getattributename Problem?


tinfanide

Recommended Posts

var team = {   players: [	 {name:"Fong", age:6,},	 {name:"Ken", age:7,},	 {name:"Bong", age:8,},    ]};document.write(team.players[0]);

How can I access the attribute name in this array? (like the "name" in players) Online I found an example but wonder if I need to write another function to get access to attribute names?

var obj = {a:1,b:2,c:3,getPropName:getProp}function getProp(n){var i=0;for(p in obj){if(i++==n) return p}}alert(obj.getPropName(0))

Link to comment
Share on other sites

you can use .name or ['name'] on the end, like
for (var i=0, j=team.players.length; i<j; i++) {	alert('name: '+team.players[i].name+'\nage:'+team.players[i]['age'])}

Sorry. I haven't expressed myself clearly.I mean to get the name of the attribute
for (var i=0, j=team.players.length; i<j; i++) {	    alert(  /*	  this part 					   */ +team.players[i].name+'\nage:'+team.players[i]['age'])}

I wonder if I can get the attribute name (e.g. name) without coding

"name"

I've actually found a similar solution online, but do not know how to apply it in this multi-dimensional array

var obj = {a:1,b:2,c:3,getPropName:getProp}function getProp(n){var i=0;for(p in obj){if(i++==n) return p}}alert(obj.getPropName(0))

Thanks.

Link to comment
Share on other sites

ohh right, you can change "for (p in obj)" to "for (p in team.players[0])" which will check the properties of the first object in the team.players array. or you could send the object as a parameter:

function getPropName(object, n) {	var i = 0	for (var prop in object) {		if (i++ == n) return prop	}} alert( getPropName(team.players[0], 0) ) // 'name'alert( getPropName(team.players[0], 1) ) // 'age'

Link to comment
Share on other sites

Yes, very helpful of you. It really improves my understanding of JSON, especially when I could hardly find any good JSON tutorial online.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...