How to get the name of the current JSON property when iterating through them in JavaScript?

I have an internal JSON object inside a variable:

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 repeat them for each cycle:

for (var piece in chessPieces){
    //some code
}

How do I get the current name? For example, we are currently on the first element (piece = 0): chessPiece[piece].GiveMeTheName==>, which leads to the string "pw-1".

I really intend to pass the current element to the function because I need to check something, so it will 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 also use jQuery in my project, so if something can be used there in this library, let me know.

Thanks in advance!:)

+5
source share
3 answers

. piece ? for ... in JavaScript .

, for (var piece in chessPieces) console.log(piece);, p-w-1, p-w-2 ..

+2

$. each (obj, fn). .

$.each(chessPieces, function(key, value) {

   //key = "p-w-1"
   //value = { "role":"pawn", ... }
   //this === value

});
+7
for (var piece in chessPieces){
    alert(piece)
}
+4
source

All Articles