How to get name of current JSON property while iterating through them in JavaScript?
I have JSON object inside variable like this:
var chessPieces = {
"p-w-1" : {
"role":"pawn",
"position":{"x":1, "y":2},
"state":"free",
"virgin":"yes"
},
"p-w-2" : {
"role":"pawn",
"position":{"x":2, "y":2},
"state":"free",
"virgin":"yes"
},...
};
And I'm iterating trough them with for each loop:
for (var piece in chessPieces){
//some code
}
How would I get current pieces name from this? For example, we are currently on the first element(piece = 0): chessPiece[piece].GiveMeTheName
==> which results i开发者_运维知识库n string "p-w-1".
I actually intend to pass the current element into the function, cos I need to check something, so it would look something like this:
//constructor for this function looks like this: function setPiece(piece,x,y);
function setPiece(chessPiece[piece],chessPiece[piece].position.x,chessPiece[piece].position.y){
//and here I need to get something like
piece.GiveMeTheName ==> which gives me string "p-w-1"
}
I'm also using jQuery in my project, so if there's something usable in that library, let me know.
I'd use $.each(obj, fn). The function allows access to the object key of the current element.
$.each(chessPieces, function(key, value) {
//key = "p-w-1"
//value = { "role":"pawn", ... }
//this === value
});
for (var piece in chessPieces){
alert(piece)
}
Erm. Isn't piece
already the name of the object? The for ... in
in JavaScript gives you the key name.
So when you do for (var piece in chessPieces) console.log(piece);
, it will print out p-w-1
, p-w-2
etc
精彩评论