Object from string

18 views
Skip to first unread message

kstubs

unread,
Jul 9, 2011, 4:04:54 AM7/9/11
to prototype-s...@googlegroups.com
I hope I haven't asked this before!!!!!!  OK, so if have a name string like this:

var name = 'somename' + x    // assuming x = 1

and some value = '1234'

I need the object:

{ somename1: '1234' }


But I can't figure out how to get here.  Please help.
Karl..

kstubs

unread,
Jul 9, 2011, 4:23:56 AM7/9/11
to prototype-s...@googlegroups.com
OK, I figured it out.  Here is my solution, and ultimately I need an Object, as you can see I'm extending args in the end, so is there a way to avoid creating the hash, then casting the hash to an object?

            var idx = itt + 1;
            var name = 'p_Value' + idx.toString();
            var h = $H();
            h.set(name, names[itt]);
            Object.extend(args, h.toObject());

Joseph Spandrusyszyn

unread,
Jul 9, 2011, 10:17:29 AM7/9/11
to prototype-s...@googlegroups.com

   var idx = itt + 1;
   var name = 'p_Value' + idx.toString();

   var h = {};
   h[name] = names[itt];

> --
> You received this message because you are subscribed to the Google Groups "Prototype & script.aculo.us" group.
> To view this discussion on the web visit https://groups.google.com/d/msg/prototype-scriptaculous/-/Sdi2kTKvSBsJ.
> To post to this group, send email to prototype-s...@googlegroups.com.
> To unsubscribe from this group, send email to prototype-scripta...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/prototype-scriptaculous?hl=en.
>

kstubs

unread,
Jul 9, 2011, 1:15:11 PM7/9/11
to prototype-s...@googlegroups.com
Wow, you just have to love Javascript, so flexible sometimes!  What an amazing language, I tell ya.
Thanks for that shortcut ilandril!

T.J. Crowder

unread,
Jul 10, 2011, 5:22:02 AM7/10/11
to Prototype & script.aculo.us
You can even use an expression within the square brackets:

var idx = itt + 1;
var h = {};
h['p_Value' + idx.toString()] = names[itt];

...but you probably want that `name` variable for something else
anyway.

This is all a consequence of the fact that object property names are
strings, and so these all set the same property of `a` to `bar`:

a.foo = bar;
a['foo'] = bar;
x = 'f'; a[x + 'o' + 'o'] = bar;

These are also identical:

a[0] = bar;
a['0'] = bar;

...and in fact, we all use the fact that a number within the brackets
is converted to a string property name all the time, whenever we use
an "array" -- because JavaScript arrays aren't really arrays at all:
http://blog.niftysnippets.org/2011/01/myth-of-arrays.html

FWIW,
--
T.J. Crowder
Independent Software Engineer
tj / crowder software / com
www / crowder software / com
Reply all
Reply to author
Forward
0 new messages