我在java中有这样的地图:
"{one=Print, two=Email, three=Download, four=Send to Cloud}";
我需要在jquery中将上面的字符串转换为数组并循环数组并获取相应的键和值
答案 0 :(得分:0)
使用String#slice
,String#trim
,Array#forEach
和String#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)
答案 1 :(得分:0)
这是一个简单的黑客攻击:
let arr = jsons.replace('{','').replace('}','').split(',')
arr.map((each)=>{let newVal = each.split('='); return {key: newVal[0], value: newVal[1]}})
答案 2 :(得分:0)
试试这个:
function convertString(string) {
return string.split(', ').map(function(a) {
var kvArr = a.split('=');
return {key: kvArr[0], value: kvArr[1]};
};
}
function convertString(string) {
string = string.slice(1, string.length - 1);
return string.split(', ').map(function(a) {
var kvArr = a.split('=');
return {key: kvArr[0], value: kvArr[1]};
});
}
alert(JSON.stringify(convertString("{one=Print, two=Email, three=Download, four=Send to Cloud}")));