Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 769
Vlad Dogaru Avatar asked May 31 '11 18:05

Vlad Dogaru


People also ask

How do you check if a property is present in an object JavaScript?

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 .

How do you iterate over the properties of objects?

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.

What is property name in JSON?

In JSON, the “keys” must always be strings. Each of these pairs is conventionally referred to as a “property”.


1 Answers

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

});
like image 66
John Strickler Avatar answered Sep 23 '22 23:09

John Strickler