wmarquardt wmarquardt - 16 days ago 5
Javascript Question

Convert serialized data to array or object

I have a string like this:

(redMultiplier=0, greenMultiplier=0, blueMultiplier=0, alphaMultiplier=1, redOffset=0, greenOffset=102, blueOffset=51, alphaOffset=0)


I need to convert this string to array (or object). And I have a lot of strings like this to convert to array too. Is there any way to automatically convert a string like this to javascript array?

Answer

this function will return a object when you transmit a string as it's parameter:

function convert(str){
    str = str.replace(/\(|\)/g,'');
    var arr = str.split(',');
    var obj = {};
    for (var i = 0; i < arr.length; i++) {
      var singleArr = arr[i].trim().split('=');
      var name = singleArr[0];
      var value = singleArr[1]-0;
      if (obj[name] == undefined) {
        obj[name] = value;
      }
    }
    return obj;
  }

the obj like Object {redMultiplier: 0, greenMultiplier: 0, blueMultiplier: 0, alphaMultiplier: 1}

Comments