如何在JavaScript中迭代它们时获取当前JSON属性的名称?

Hap*_*ppy 5 javascript each jquery json for-loop

我在变量里面有JSON对象,如下所示:

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"
    },...
};
Run Code Online (Sandbox Code Playgroud)

我正在为每个循环迭代它们:

for (var piece in chessPieces){
    //some code
}
Run Code Online (Sandbox Code Playgroud)

我如何从中获取当前的名称?例如,我们当前在第一个元素(piece = 0):chessPiece[piece].GiveMeTheName==>,这导致字符串"pw-1".

我实际上打算将当前元素传递给函数,因为我需要检查一下,所以它看起来像这样:

//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"
}
Run Code Online (Sandbox Code Playgroud)

我也在我的项目中使用jQuery,所以如果该库中有可用的东西,请告诉我.

Joh*_*ler 7

我会使用$ .each(obj,fn).该函数允许访问当前元素的对象键.

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

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

});
Run Code Online (Sandbox Code Playgroud)


Pwn*_*nna 2

嗯。不是piece已经有对象的名称了吗?JavaScript 中的for ... in为您提供键名。

所以当你这样做时for (var piece in chessPieces) console.log(piece);,它会打印出来p-w-1p-w-2等等