gpt4 book ai didi

javascript - 在 jquery 中将 Map 转换为数组

转载 作者:行者123 更新时间:2023-12-01 05:24:01 25 4
gpt4 key购买 nike

我在java中有这样的 map :

"{one=Print, two=Email, three=Download, four=Send to Cloud}";

我需要在jquery中将上面的字符串转换为数组并循环数组并获取相应的键和值

最佳答案

使用String#slice , String#trim , Array#forEachString#split方法。

var str = "{one=Print, two=Email, three=Download, four=Send to Cloud}";

str
// remove the space at start and end
.trim()
// get string without `{` and `}`
.slice(1, -1)
// split by `,`
.split(',')
// iterate over the array
.forEach(function(v) {
// split by `=`
var val = v.trim().split('=');
console.log('key : ' + val[0] + ", value : " + val[1])
})

<小时/>

更新:如果你想生成一个对象,那么使用Array#reduce方法。

var str = "{one=Print, two=Email, three=Download, four=Send to Cloud}";

var res = str
.trim()
.slice(1, -1)
.split(',')
.reduce(function(obj, v) {
var val = v.trim().split('=');
// define object property
obj[val[0]] = val[1];
// return object reference
return obj;
// set initial parameter as empty object
}, {})

console.log(res)

关于javascript - 在 jquery 中将 Map<String,String> 转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40882019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com