0

This is a JSON code that is generated on the server side and sent through websockets to the client as a string:

{
    "zw_ob-k7g8ahcvFzAAAA":{
        "position":{  
             "x":319,
             "y":135
        },
        "mass":324,
        "name":21,
        "color":"#5058a9"
    },
    "uTFD8dw0OiqD4ErzAAAB":{
        "position":{  
            "x":473,
            "y":348
        },
        "mass":59,
        "name":7,
        "color":"#e79448"
    },
    "CvMRJ6rEFYoU1vajAAAC":{
        "position":{  
            "x":25,
            "y":604
      },
        "mass":147,
        "name":18,
        "color":"#cef6c3"
    },
    "_e6TLrfubHqf-7esAAAD":{
        "position":{  
            "x":146,
            "y":417
        },
        "mass":320,
        "name":13,
        "color":"#ab7aa0"
    }
}

On the client I use JSON.Parse to parse this string into json structure.

planetsData = JSON.parse(data.planets);

for(var p in planetsData){

    var playerName = p;
    alert(p.position) //says "undefined" 
    var planetColor = p.color;
    var planetName = p.name;

    var planet = new Planet();
}

I can successfully get p, p.color and p.name, but for some reason it says that p.position is undefined, hence I can't access p.position.x or p.position.y parameters.

5
  • What's the output of console.log(p)? Commented Oct 13, 2018 at 13:36
  • @AlbertoTrindadeTavares console.log P works. Outputs the key Commented Oct 13, 2018 at 13:37
  • 2
    p is the key and not the complete object Commented Oct 13, 2018 at 13:39
  • planetsData[p].position Commented Oct 13, 2018 at 13:46
  • Yes my mistake was that as Andreas said, P is just a key. Commented Oct 13, 2018 at 13:48

1 Answer 1

4

Change this line alert(p.position) to this:

 alert(planetsData[p].position);

And for other usages too.

Also you can add this:

p=planetsData[p];

At first of loop and now use your code itself:

for(var p in planetsData){
   var playerName = p;

   p=planetsData[p]; //add this line here

   alert(p.position) ;
   var planetColor = p.color;
   var planetName = p.name;

   var planet = new Planet();
 }
Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome @Nick :) I'm glad that helped you. You can mark the answer as accepted if it was useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.