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.
JavaScript provides you with three common ways to check if a property exists in an object: Use the hasOwnProperty() method. Use the in operator. Compare property with undefined .
Method 1: Using for…in loop: The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-Symbol iterable properties of an object. Some objects may contain properties that may be inherited from their prototypes.
In JSON, the “keys” must always be strings. Each of these pairs is conventionally referred to as a “property”.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With