3

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

3
  • what is the problem? Commented Nov 30, 2016 at 6:54
  • show what you have tried so far ? Commented Nov 30, 2016 at 6:56
  • Possible duplicate of converting hash map to array Commented Nov 30, 2016 at 7:16

3 Answers 3

1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

.reduce() is not supported in ie8 is there any alternative for this
0

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]}})

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.