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 in 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.
Erm. Isn’t
piecealready the name of the object? Thefor ... inin JavaScript gives you the key name.So when you do
for (var piece in chessPieces) console.log(piece);, it will print outp-w-1,p-w-2etc