user3198603
user3198603

Reputation: 5836

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 ?

Upvotes: 1

Views: 6078

Answers (1)

Florian Schaetz
Florian Schaetz

Reputation: 10662

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.

Upvotes: 1

Related Questions