2 Replies Latest reply on Nov 14, 2008 1:14 AM by woutek

    String to Object ?

      I'd like to achieve something as below, so having a string value that I can convert to an object. Reason behind his is that I will get the string values from an external source, so I'm looking at an easy way to convert them in an object. It's probably fairly simple but I can't figure out how to do this.

      var s:String = "V1:30, V2:72, V3:86, V4:55";
      var obj:Object = {s}; // of course this doesn't work, but you get the idea ...
        • 1. Re: String to Object ?
          Level 7
          woutek wrote:
          > I'd like to achieve something as below, so having a string value that I can
          > convert to an object. Reason behind his is that I will get the string values
          > from an external source, so I'm looking at an easy way to convert them in an
          > object. It's probably fairly simple but I can't figure out how to do this.
          >
          > var s:String = "V1:30, V2:72, V3:86, V4:55";
          > var obj:Object = {s}; // of course this doesn't work, but you get the idea ...
          >

          If you mean that you want obj to look like { V1: 30, V2: 72, V3: 86, V4: 55 },
          and you are sure of the format of your strings, this would probably work:

          function stringToObject(s:String):Object
          {
          var o:Object = {};
          for each (var pair:String in s.split(', '))
          {
          var a:Array = pair.split(':');
          o[ a[0] ] = parseInt(a[1]);
          }
          return o;
          }

          Not necessarily efficient, but unless your strings are ridiculously long or
          you're doing this in a tight loop, it should be OK.

          - Adam
          • 2. Re: String to Object ?
            Level 1
            Man, you saved my day ! This works like a charm... If you're ever in the lovely country of Belgium let me know and I buy you a big beer :-)