SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    SitePoint Zealot sappo's Avatar
    Join Date
    Sep 2005
    Posts
    142
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    string to object, simple right?

    Hey all,

    I thought this would be a breeze, but it's completely stumped me.

    Basically I have have a normal variable which the contains looks like -> name1:"dude",name2:"sweet"...

    And I need this to populate an object with this:

    myobject = {myvariable};

    But of course this doesn't work, any ideas?
    eval, maybe?
    Check out my Movie Trailers website - Popcorn Trailers

  2. #2
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    eval() would work.

    You could also split() on the comma, and then split the colons, as long as your values will never contain those characters.

    A regular expression would also work well here.

  3. #3
    SitePoint Zealot sappo's Avatar
    Join Date
    Sep 2005
    Posts
    142
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I've tried: myobject = {eval(myvariable)}; but it didn't work.

    I understand the spilt() concept, and know how to do all the breaking apart, but I think I would be left with the same problem, wouldn't I?

    if you know of an example of how to do this I would greatly appreciate it...
    Check out my Movie Trailers website - Popcorn Trailers

  4. #4
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What do you mean by normal variable? You have a string? And the contents are name1:"dude",name2:"sweet"? And you want to parse it into a javascript object?

    Assuming yes to all of the above, you could do:
    Code javascript:
    var obj = eval("{" + str + "}");


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •