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
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
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)
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}")));