简体   繁体   中英

convert java map to javascript map and loop over to get keys/values?

In java i have hashmap

Map<String , List<Employee>> employeeMap = new HashMap<String , List<Employee>> ();
employeeMap.put(1, new Employee());
........

I am adding it in request attribute

Now in javascript i need to loop over over map, to get keys and values

Here what i tried

Approach 1 :-

var empMap = '${employeeMap}'; 
//here is the example value of map in javascript which i see while debugging
//var empMap = {emp1_100=[com.Employee@5b7b4bc5], emp2...

for (var key in empMap) {
    alert(key + ': ' + empMap[key]);
}

But getting syntax error

 SyntaxError: missing : after property id

Approach 2 :- with jquery

 var jsonMap  = $.stringify(empMap);

 $.each( jsonMap, function( key, value ) {
  alert( key + ": " + value );
});

But its not working either. It print some characters.

I am not sure what i am missing here ?

Looks like you are simply writing whatever the .toString() method of your Map returns to the request, which is not a good idea in the first place.

If I were you, I would convert your Map into a JSON object (there various ways to do that, depending on your system) and then append the String representation of this JSON object to the request, because then you can simply call "JSON.parse( ... );" in JavaScript to transform it into a JavaScript object without having to do any parsing yourself.

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