0

I have JSON: {"status":"ok","squares":{"3x13":"0","3x12":0,"4x12":0,"2x13":0,"4x13":0,"4x14":2}}

How can i translate this to key-value array in javascript?

        for (var s in s.squares) {
            console.log(s);
        }

gives only keys, like 3x13, 3x12. How get the values?

P.S. Sorry for bad Engish.

0

2 Answers 2

2

your loop for (var s in s.squares) will iterate each property of the object refered to by s.squares to get the value as well you simply have to do s.squares[s] so the loop would be something like:

for (var key in s.squares) {
   var value = s.squares[key];
}

how ever you'd probably want to safe guard yourself a bit and write the itertion like:

var squares = s.squares;
for (var key in squares) {
   if(squares.hasOwnProperty(key)){
      var value = squares[key];
   }
}
Sign up to request clarification or add additional context in comments.

Comments

2

If the JSON is a String, you can use jQuery.parseJSON to convert it to a JSON Object. If you have the Object, use

for (var key in json) {
    console.log("key:", key, "value:", json[key]);
}

Comments

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.