user3044552 user3044552 - 2 days ago 5
jQuery Question

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

Answer

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)

Comments