Home javascript How to iterate over the elements of an object?

How to iterate over the elements of an object?

Author

Date

Category

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];

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions