简体   繁体   中英

JavaScript - How can I iterate object that is actually a map?

I got a JSON object from the server that is actually:

Map<Integer, Integer>

How can I iterate over it and get the key and value in each iteration?

Thanks!

Just like that:

var key, response = {1:3, 5:6, 3:8}; // sample response of your server
for (key in response) {
    if (response.hasOwnProperty(key)) {
        console.log("key: " + key + ", value: " + response[key]);
    }
}

Output:

key: 1, value: 3
key: 3, value: 8
key: 5, value: 6

Once you convert the JSON string to an object you can use a foreach style for loop

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM