JSON is available: {"Gray": "11", "Black": "18"}
.
How to iterate over it in a loop so that the key and value can be used?
(key = & gt; value as in php foreach loop)
Answer 1, authority 100%
This example: {"Gray": "11", "Black": "18"}
is an object, you can use the loop for..in
. This will check all enumerated properties, including ancestor properties
var o = {
"Gray": "11",
"Black": "18"
};
for (var key in o) {
console.log (key, ':', o [key]);
}
Answer 2, authority 30%
Better to use jquery $ .each function
$. each (JSON.parse ('{"Gray": "11", "Black": "18 "} '), function (key, value) {
console.log (key + "" + value);
})
Answer 3, authority 30%
var json = '{"Gray": "11", "Black": "18 "} ';
// Convert JSON to object
var obj = JSON.parse (json);
// Working with the object
for (var prop in obj) {
console.log (prop, obj [prop]);
}
Answer 4, authority 20%
use the construction for..in
var data = {"Gray": "11", "Black": "18"};
for (color in data)
alert ("Color:" + color + ", Value:" + data [color];