Reputation: 47
I have Map in java like this :
"{one=Print, two=Email, three=Download, four=Send to Cloud}";
I need to convert above string to array in jquery and loop the array and fetch respective key and value
Upvotes: 3
Views: 1481
Reputation: 115212
Use String#slice
, String#trim
, Array#forEach
and String#split
methods.
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])
})
UPDATE : If you want to generate an object then use Array#reduce
method.
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)
Upvotes: 1
Reputation: 833
Try this:
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}")));
Upvotes: 0
Reputation: 1468
Here is a simple hack:
let arr = jsons.replace('{','').replace('}','').split(',')
arr.map((each)=>{let newVal = each.split('='); return {key: newVal[0], value: newVal[1]}})
Upvotes: 0