javascript - 如何将下面的 hashMap<String, String> 转换为可用的 JS 对象?

标签 javascript java jquery html jstl

长话短说。

我们的后端团队向我提供了一个 hashMap,其输出如下。

{12=其他服务(协助)、2=其他服务、4=收集、17=获取新服务(为我)、19=获取新服务(为我的企业)}

我是一名前端开发人员,从未使用过这样的字符串。由于“=”,我无法使用 jquery.split() 拆分它

在网上搜索时,我找到了很多问题的答案,但无法使其发挥作用,即使它实际上是我问题的正确答案。

以下是我尝试过的。 ${departmentHash} 就是一个例子。我认为我的实际代码不会产生任何影响。

How to iterate HashMap using JSTL forEach loop?

<c:forEach var="department" items="${departmentHash}">
    Country: ${department.key}  - Capital: ${department.value}
</c:forEach>

上面没有向 ${department} 返回任何内容

其他链接有类似的答案,但我无法正常工作。

How to loop through a HashMap in JSP?
How to iterate an ArrayList inside a HashMap using JSTL?

我的问题措辞可能有误,因此如果有人能为我提供正确的链接或我的问题的答案,我将不胜感激。

最佳答案

由于关键部分中存在整数(12、2、4 等),因此无法解析您提供的字符串。

如果您以字符串形式获取 HashMap 数据,则可以在 javascript 中尝试如下操作:

var str = '{12=Other Services (Assisted), 2=Other Services, 4=Collect, 17=Get New (For Me), 19=Get New (For My Business)}';

str = str.replace('{','');
str = str.replace('}','');// these lines will remove the leading and trailing braces

var arr = str.split(','); // this will give you an array of strings with each index in the format "12=Other Services (Assisted)"

arr.forEach(function(item){
    // here you can split again with '=' and do what is required
    var s = item.split('=');
    var obj = {key: s[0], value:s[1]}; // this is up to your implementation

})

关于javascript - 如何将下面的 hashMap<String, String> 转换为可用的 JS 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44943228/

相关文章:

javascript - 解析美元金额的 HTML 源代码,然后将最高金额设置为 var

javascript - 如何让用户能够添加另一个选择数据?

javascript - 使用 javascript 和正则表达式从文本中获取数字

javascript - 为什么在我使用 jQuery 时滚动到顶部不起作用?

php - 使用php将数据从mysql传递到modal

javascript - 从node js服务器向客户端发送axios post请求错误消息

java - 访问 Spring Filter/HandlerInterceptor 多部分和参数(表单字段)

java - 使用 Java 而不是 Javascript 作为 DOM 操作语言的浏览器

java - 无法更改背景 JFrame

javascript - 修复了 Navbar 子下拉菜单无法正确显示的问题