There are JSON: {"Gray":"11","Black":"18"} .

How to cycle through it so that you can use a key and a value?
(key => value, as in the foreach loop in php)

    4 answers 4

    This example: {"Gray":"11","Black":"18"}

    is an object, to bypass the properties of an object, you can use the for..in . This will check all enumerated properties, including the properties of ancestors.

     var o = { "Gray": "11", "Black": "18" }; for (var key in o) { console.log(key, ':', o[key]); } 

    You can also use the Object.keys function .

     var o = { "Gray": "11", "Black": "18" }; Object.keys(o).forEach(function(key) { console.log(key, ':', this[key]); }, o); 

    • Thank. What I was looking for - Nazar Vozniy

    Better to use the jquery $ .each function

     $.each(JSON.parse('{"Gray":"11","Black":"18"}'), function(key, value) { console.log(key + " " + value); }) 
    • no, it’s not better, firstly, there’s no mention of jQuery in the question, so this one may not be applied in principle, secondly, inside it is used the same for..in - Grundy
    • No , yes, but it is more convenient to use - user3240895
    • what is more convenient? - Grundy

     var json = '{"Gray":"11","Black":"18"}'; // Конвертируем JSON в объект var obj = JSON.parse(json); // Работаем с объектом for (var prop in obj) { console.log(prop, obj[prop]); } 

      use the for..in construct

       var data = {"Gray":"11","Black":"18"}; for (color in data) alert("Color: " + color + ", Value: " + data[color];