简体   繁体   English

将Java映射转换为javascript映射并循环获取键/值?

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

In java i have hashmap 在Java中我有哈希图

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 现在在javascript中,我需要遍历地图,以获取键和值

Here what i tried 这是我尝试过的

Approach 1 :- 方法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 方法2:-使用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. 看起来您只是在编写Map的.toString()方法返回到请求的任何内容,这首先不是一个好主意。

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( ... );" 如果您是我,我会将Map转换为JSON对象(有多种方法,具体取决于您的系统),然后将此JSON对象的String表示形式附加到请求中,因为这样您就可以简单地调用“ JSON。 parse(...);” in JavaScript to transform it into a JavaScript object without having to do any parsing yourself. 在JavaScript中将其转换为JavaScript对象,而无需自己进行任何分析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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