Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Map<String,String> into array in jquery

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

like image 865
user3044552 Avatar asked Apr 15 '26 06:04

user3044552


1 Answers

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)
like image 146
Pranav C Balan Avatar answered Apr 16 '26 20:04

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!